import { Component, OnInit, ViewChild } from '@angular/core';
import { config } from '../../shared/smartadmin.config';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入
import { NotificationService } from "../../shared/utils/notification.service";
import { CompanyTreeCarComponent } from '../../shared/companyTreeCar/companyTreeCar.component';
import { log } from 'console';


declare var $: any;
declare var BMap: any;
declare var toWGS84: any;
declare var toMapPoint: any;
declare var Viewer: any;
declare var echarts: any;
@Component({
	selector: 'sa-car-running',
	templateUrl: './car-running.component.html',
	styleUrls: ['./car-running.css', './timeline.css']
})
export class CarRunningComponent implements OnInit {

	validatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			selectedCompanyName2: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择公司'
					}
				}
			}
		}
	}
	factoryvalidatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			// valid : 'glyphicon glyphicon-ok',
			// invalid : 'glyphicon glyphicon-remove',
			// validating : 'glyphicon glyphicon-refresh'
		},
		fields: {
			selectedCompanyName3: {
				trigger: 'change',
				validators: {
					notEmpty: {
						message: '请选择公司'
					},
					remote: {
						message: '该公司已存在',
						url: config.BaseURL + "factory/validateCompanyId.html",
						delay: 200,
						data: (validator) => {
							return {
								id: this.factory.id ? this.factory.id : "",
								companyId: this.selectedCompanyId3,
							};
						},
					}
				}
			},
			r: {
				validators: {
					notEmpty: {
						message: '请输入有效半径'
					},
					callback: {
						callback: function (value, validator, $field) {
							if (value) {
								if (!Number(value) || Number(value) <= 0 || value.split(".").length > 1) {
									return {
										valid: false,
										message: '半径请输入大于0的整数'
									}
								} else {
									return true
								}
							} else {
								return true
							}

						}
					}
				}
			},
			lng: {
				trigger: 'change',
				validators: {
					notEmpty: {
						message: '请输入经度'
					},
					stringLength: {
						max: 18,
						message: '长度在18以内'
					},
					callback: {
						callback: function (value, validator, $field) {
							if (value.length < 17) {
								if (value) {
									var reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,14})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,14}|180)$/;
									if (!reg.test(value)) {
										return {
											valid: false,
											message: '经度有误'
										}
									} else {
										return true;
									}
								} else {
									return true;
								}
							} else {
								return true;
							}

						}
					},
				}
			},
			lat: {
				trigger: 'change',
				validators: {
					notEmpty: {
						message: '请输入纬度'
					},
					stringLength: {
						max: 18,
						message: '长度在18以内'
					},
					callback: {
						callback: function (value, validator, $field) {
							if (value.length < 17) {
								if (value) {
									var reg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,14}|90\.0{0,14}|[0-8]?\d{1}|90)$/;
									if (!reg.test(value)) {
										return {
											valid: false,
											message: '纬度有误'
										}
									} else {
										return true;
									}
								} else {
									return true;
								}
							} else {
								return true;
							}

						}
					},
				}
			},
		}
	}
	setFrequencyValidatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			// valid : 'glyphicon glyphicon-ok',
			// invalid : 'glyphicon glyphicon-remove',
			// validating : 'glyphicon glyphicon-refresh'
		},
		fields: {
			deviceId: {
				validators: {
					notEmpty: {
						message: '请输入设备编号'
					}
				}
			},
		}
	}

	ULvalidatorOptions = {
		excluded: [":disabled"],
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			ULselectedCompanyName: {
				trigger: "change",
				validators: {
					notEmpty: {
						message: '请选择公司'
					}
				}
			},
			time: {
				validators: {
					notEmpty: {
						message: '请输入上传频率'
					}
				}
			}
		}
	}
	tableData = []; //table数据
	selected: any[] = []; //row选择的数据
	totalCount = 0; //分页总条数
	curPage = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey = ''; //搜索keyword
	selectedRow = false;//记录是否选择了row
	sortType: string = '';
	filterType: string = ''; //过滤条件
	// 设备升级的参数
	firmPageSize: number = 10; // 设备升级弹窗固件表的
	firmCurPage: any = 1; // 分页当前页
	firmtotalCount: number = 0; // 分页总条数
	newProtoVersion: string = '2'; //设备升级的版本
	hardwareVersion: string = '';//硬件升级的版本
	versionNum: string = '';// 版本号
	firmuseTypeL2: string = ""; //车辆类型
	firmcompanyId: string = ""; //公司
	firmTableData: any = []; //表单数据
	firmselected: any[] = []; //固件管理row选择的数据
	// 设置厂区在线的参数
	onlineSetCompanyId: string = ""; // 公司
	factoryOnlinePageSize: number = 10; // 厂区在线表的页的条数
	factoryOnlineCurPage: any = 1;      // 当前页码
	factoryOnlinetotalCount: number = 0; // 分页总条数
	factoryOnlineSearchKey: string = ""; // 关键字搜素
	factoryOnlineTableData: any = []; // 厂区设置在线的表单数据
	selectedCompanyName3: string = ""; // 添加厂区的公司名
	selectedCompanyId3: string = ""; // 添加厂区的公司id
	// 离线统计的参数
	offlinePageSize: number = 10; // 厂区在线表的页的条数
	offlineCurPage: any = 1;      // 当前页码
	offlinetotalCount: number = 0; // 分页总条数
	// offlineSearchKey: string = ""; // 关键字搜素
	offlineTableData: any = []; // 厂区设置在线的表单数据
	offlineCompanyId: any = ""; // 离线的公司Id
	offlineDeviceId: any = ""; // 离线设备ID
	offlineType: any = "3"; // 离线类型 1:从未上线 2：当天离线 3：离线车辆 4：离线1-3天 5：离线3-5天 6：离线5-7天 7：长期离线
	alarmType: any = "" // 警报类型 0 无警报 1 断电警报 2 离线警报 3 异常断电
	hardVersion: any = "" // 硬件版本
	offline_startTime: any = ""
	offline_endTime: any = ""
	isHex = false;//是否开启16进制模式
	specifyId = {
		picker1: 'datetimepicker3',
		picker2: 'datetimepicker4'
	}
	specifyTime = {
		startTime: '',
		endTime: '',
	}
	offlineCountArray: any = [0, 0, 0, 0, 0, 0, 0] // 离线统计的数量
	versionArr = [{
		id: '1',
		name: '第一代'
	}, {
		id: '2',
		name: '第二代'
	}, {
		id: '3',
		name: '808协议'
	}];
	binData = [];
	protocolVersion = '2';//版本
	protocolVersionName = '第二代';
	binId = ''; //固件号
	binName = ''; // 固件名称
	deviceId = ''; //设备id
	runStatus: boolean = true; //存储设备在线状态
	isAuto: boolean = false; //是否自动清零
	isZero: boolean = false; //是否清零
	selectedCompanyName = ''; //公司名称
	selectedCompanyId = '';//公司ID
	companyList = [];//公司数据
	online = '0'; //是否在线
	startTime = '';//开始时间
	endTime = ''; //结束时间
	weightForReal: '';//实际重量
	matlabParam: '1000,200,5,2,0';//Matlab参数
	factorResult: '';//标定系数结果
	moreChannelsChecked: false;//是否开启32通道模式
	channelObj = {} // 通道对象
	autoSetChannelParam: string = '';//自动设置通道系数输入值
	isOpenAutoSetChannel: boolean = false;//是否显示自动设置通道系数模块,默认隐藏
	btnData = []; //权限按钮集合
	systemUpgrade: boolean = false;//固件管理权限
	hasRowDeletePermission: boolean = false;//删除权限
	carDeviceId = '';
	carNumber = '';
	config: any = {//参数配置
		deviceId: '',
		weight: '',
		upload: '',
		binVersion: '',//固件版本
		algorithmVersion: '',//算法版本
		bootLoaderVersion: '',
		longitude: '',
		latitude: '',
		speed: '',
		azimuth: '',//方位角
		satellites: '',//卫星数
		GPSstrength: '',//GPS信号强度
		ICCId: '',
		GSMstrength: '',//GSM信号强度
		Ip: '', //IP地址
		port: '',//端口号
		vcd: '',//电压
		ACCSignal: '',//ACC信号
		ioStatusOne: '',//第一路IO状态
		ioStatusTwo: '',//第二路IO状态
		ioStatusThree: '',//第三路IO状态
		params: {
			channel1: '',
			channel2: '',
			channel3: '',
			channel4: '',
			channel5: '',
			channel6: '',
			channel7: '',
			channel8: '',
			channel9: '',
			channel10: '',
			channel11: '',
			channel12: '',
			channel13: '',
			channel14: '',
			channel15: '',
			channel16: ''
		},
		serviceTime: '' //服务到期
	};
	weightFix: any = {
		isRectify: false,
		typeRectify: '1',
		factorRectify: '1',
		lastDate: '',
		status: 0
	}
	resetMatlabStartTime: string = '';
	resetSensorType: string = '';//重置传感器类型
	selectedCompanyId2: string = '';//所属公司ID
	selectedCompanyName2: string = '';//所属公司名称
	allChecked: boolean = false;//table全选状态值
	transportStatus: string = '';//运输状态
	isRepeat: boolean = false;//版本号相同重复升级
	oldVersion: string = '';//原始版本号
	expectUpdateNum = '';//升级期望数
	transportStatusText: string = '全部';
	carUseTpyeText: string = '';//车辆用途text
	is1sFrequency = '0';//筛选条件   0 全部,1 =1s  2=非1秒
	mulUpVersion: any = {
		hwVersion: '',

	};
	versionUpdataRecord: any = [];//固件升级记录
	coefUpdataRecord: any = [];//系数设置日志
	sensorList: any = []; // 设备事件模块中的传感器通道问题数组
	otherData: any = {}; // 设备事件模块中的其他数据 弥补之前的接口数据不足
	carTypeList = carTypeListObj.carTypeList
	TcarUseList = carTypeListObj.carUseList
	TcarDeatailUseList = carTypeListObj.carDeatailUseList
	carDeatailUseList: any = {
		'': '全部',
		'0000': '其他',
		'0100': '其他',
		'0101': '散装水泥罐车',
		'0102': '袋装水泥汽车',
		'0104': '袋装平板车',
		'0103': '混凝土搅拌车',
		'0105': '物资车',
		'0200': '其他',
		'0210': '后挂垃圾车[单桶]',
		'0211': '后挂垃圾车[双桶]',
		'0212': '后挂垃圾车[三桶]',
		'0213': '侧挂垃圾车[链条]',
		'0214': '侧挂垃圾车[拉杆]',
		// '0201':'侧挂式垃圾车',  //该数据已删除
		// '0202':'压缩式垃圾车', //该数据已删除
		'0203': '勾臂车垃圾车',
		'0204': '摆臂式垃圾车',
		'0208': '尾板垃圾车[8桶]',
		'0206': '尾板垃圾车[4.2M]',
		'0205': '尾板垃圾车[4.2M平板]',  //名字更改 旧名称：餐厨式垃圾车
		'0207': '尾板垃圾车[4.2M不封顶]',
		'0215': '压缩式垃圾车[整车]',
		'0209': '三轮垃圾车',
		'0300': '其他',
		'0301': '箱式货车[4.2M]',
		'0302': '箱式货车[7.6M]',
		'0303': '箱式货车[9.6M]',
		'0304': '依维柯',
		'0400': '其他',
		'0401': '渣土车[2轴]',
		'0402': '渣土车[3轴]',
		'0403': '渣土车[4轴]',
		'0500': '其他',
		'0501': '箱式挂车',
		'0502': '平板挂车',
		'0601': '煤炭车',
		'0701': '骨料车',
		'0801': '混凝土搅拌车'
	}
	isViewer: boolean = false; //默认隐藏;
	isShowSignalTesting: boolean = false; //信噪比检测权限按钮默认隐藏
	constructor(private jsonApiService: JsonApiService, private router: Router, private notificationService: NotificationService) {

		// 从信息汇总跳转过来的数据
		const summaryInfoParams = JSON.parse(common.getCookie('jumpFromSummaryInfo'))
		if (summaryInfoParams) {
		  this.searchKey = summaryInfoParams.deviceId
		  this.selectedCompanyName = summaryInfoParams.companyName
		  this.selectedCompanyId = summaryInfoParams.companyId
		  common.clearCookie('jumpFromSummaryInfo')
		}
	 }
	// 引入子组件
	@ViewChild('ctcComponent')
	companyTreeCarComponent: CompanyTreeCarComponent
	ngOnInit() {
		this.initBtn();
		// this.initofflineCarTree();
		this.reaustHeader(); //请求表头
		if (this.inputParam.length == 0) { this.querySensor(); }// 请求传感器列表接口
		this.load();
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				this.selectCompany();//初始化select 2 车辆
				this.initBinSelect2()
				this.initMap();
				this.initBin().then(() => { this.initBinSelect2() });//初始化select 2 版本文件
				this.initCar()
			})
		})
		System.import('assets/js/viewer/viewer.js').then(
			() => {
				System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
					() => {
						System.import('assets/js/viewer/viewer.css').then(() => {
						})
					})
			})
		this.initChannel()
	}

	// 初始化通道数据
	initChannel() {
		for (let i = 1; i < 33; i++) {
			this.channelObj[`channel${i}`] = ''
		}
	}

	//请求传感器类型的接口
	querySensor() {
		this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe(data => {
			if (data.success) {
				this.inputParam = data.data
			}
		})
	}
	inputParam: any = [];
	//公司选中回调
	companySelected(data) {
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
	}
	ngOnDestroy() {
		var body = document.getElementsByTagName('body')[0];
		document.onclick = null;
		body.onclick = null;
	}
	//批量升级
	mulupdata(val) {
		if (this.protocolVersion != '2') {
			this.jsonApiService.message('目前只支持第二代批量升级');
			return;
		}
		if (!this.binId) {
			this.jsonApiService.message('请选择设备升级的bin版本号');
			return;
		}
		val.show();
		this.load_company();
		var tree_box2 = document.getElementById('tree_box2');
		var company2 = document.getElementById('company2');
		//公司树弹窗显示隐藏交互事件
		var body = document.getElementsByTagName('body')[0];
		body.onclick = function (e: any) {
			if (!(e.target === company2 || e.target.className === 'jstree-node  jstree-open' || e.target.className === 's_company_root_box' || e.target.className === 'treeSearchInputBox' || e.target.className === 'treeSearchInput' || e.target.className === 'jstree-children' || e.target.className === 's_del_icon' || e.target.className === 'jstree-node  jstree-leaf' || e.target.className === 'jstree-icon jstree-ocl' || e.target.className === 'vision_tree' || e.target.className === 'jstree-node jstree-leaf jstree-closed')) {
				tree_box2.className = tree_box2.className.replace("tree_open", "");
			}
		}
	}
	//批量升级取消事件
	cancelUpdata(val) {
		val.hide();
		this.selectedCompanyName2 = '';
		this.selectedCompanyId2 = '';
		// this.oldVersion = '';
		// this.expectUpdateNum = '';
		this.isRepeat = false;
		$('#company2').val("");
		this.companySearch2();
		$("#mulUpdataFrom").data('bootstrapValidator').resetForm();
	}
	//批量升级提交
	updataSubmit(val) {
		if (this.selectedCompanyName2) {
			let flag: boolean = false;
			for (let item of this.companyList) {
				if (item.text === this.selectedCompanyName2) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				this.jsonApiService.message('公司[' + this.selectedCompanyName2 + ']不存在,请重新选择公司');
				return;
			}
		}
		$('#mulUpdataFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#mulUpdataFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.carUseTpyeText = this.getArrLable($('#carTypeSelect2').val())
			val.show();
		}
	}
	getArrLable(key) {
		return this.carDeatailUseList[key];
	}
	onSubmit(val) {
		this.updataSubmit(val);
	}
	//批量升级取消
	cancelMulupdata(val) {
		val.hide();
	}
	//批量升级提交
	mulupdataSubmit(val) {
		let useTypeL2 = $('#carTypeSelect2').val();
		let isRepeat: string = '0';
		if (this.isRepeat) { isRepeat = '1'; };
		let reqdata = 'companyId=' + this.selectedCompanyId2 + '&protocolVersion=' + this.protocolVersion + '&binId=' + this.binId + '&weight=' + this.transportStatus + '&useTypeL2=' + useTypeL2 + '&isRepeat=' + isRepeat + '&hwVersion=' + $('#hwVersion').val() + '&oldVersion=' + this.oldVersion + '&expectUpdateNum=' + this.expectUpdateNum;
		this.jsonApiService.http('system/upgradebatch.html', reqdata).subscribe(data => {
			if (data.success) {
				val.hide()
			}
			this.jsonApiService.message(data.message);
		})
	}
	//运输状态change回调
	transportStatusChange() {
		switch (this.transportStatus) {
			case '0.0':
				this.transportStatusText = '空车';
				break;
			default:
				this.transportStatusText = '全部';
				break;
		}
	}
	//打开公司树
	companyClick2() {
		$('#tree_box2').toggleClass('tree_open');
	}

	//擦除公司所选值
	delText2() {
		this.selectedCompanyName2 = '';
		this.selectedCompanyId2 = '';
		$('#company2').val("");
		$('#company2').val('').change();
		this.companySearch2();
		this.selectIndex = '';
		this.selectCount = '';
		if ($('#tree_box2')[0].className.indexOf('tree_open') > 0) {
			$('#company2').focus();
		}
	}

	//公司树模糊搜索
	companySearch2() {
		var value = $('#treeSearchInput').val();
		this.selectIndex = '';
		this.selectCount = '';
		$("#tree2").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if (searchResult < 1) { return };
		$('.jstree-search').each(function (index, obj) {
			if (index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#vision_tree2'),
					scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#vision_tree2').height() * 0.3 });
			}
		})

		if (value) {
			this.selectIndex = 1;
			this.selectCount = $('#tree_box2').find('.jstree-search').length;
			$('#tree_box2').find('.jstree-search')[0].className = "jstree-anchor jstree-search jstree-searchCheck";
		}
	}

	selectIndex: any = '' // 选中的位置
	selectCount: any = '' // 选中的总数
	upArrow(e) {
		e.stopPropagation()
		var that = this;
		if (parseInt(this.selectIndex) == 1) {
			that.jsonApiService.message("目前已经在开始位置");
			return;
		}
		that.selectIndex = parseInt(that.selectIndex) - 1;
		$('#tree_box2').find('.jstree-search')[that.selectIndex - 1].className = "jstree-anchor jstree-search jstree-searchCheck"
		$('#tree_box2').find('.jstree-searchCheck')[1].className = "jstree-anchor jstree-search";

		let container = $('#tree_box2').find('.vision_tree');
		let _this = $('#tree_box2').find('.jstree-search').eq(that.selectIndex - 1);
		let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3;
		container.animate({ scrollTop: top });

	}
	downArrow(e) {
		e.stopPropagation()
		var that = this;
		if (parseInt(this.selectIndex) == parseInt(this.selectCount)) {
			that.jsonApiService.message("目前已经在结束位置");
			return;
		}
		let lenindex = parseInt(this.selectIndex);
		$('#tree_box2').find('.jstree-searchCheck')[0].className = "jstree-anchor jstree-search "
		this.selectIndex = parseInt(this.selectIndex) + 1;
		$('#tree_box2').find('.jstree-search')[lenindex].className = "jstree-anchor jstree-search jstree-searchCheck"

		let container = $('#tree_box2').find('.vision_tree');
		let _this = $('#tree_box2').find('.jstree-search').eq(lenindex);
		let top = _this.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3;
		container.animate({ scrollTop: top });

	}
	//公司树模糊搜索
	companySearchBtn() {
		var that = this;
		var value = $('#tree_box2').find('.treeSearchInput').val();
		$('#tree_box2').find('.treeId').eq(0).jstree(true).search(value);
		let searchResult = $('#tree_box2').find('.jstree-search').length;
		if (searchResult < 1) {
			that.jsonApiService.message('未搜索到结果');
			return;
		}
		$('#tree_box2').find('.jstree-search').each(function (index, obj) {
			console.log(index, "22222222");
			if (index < 1) { //js树搜索定位到结果的第一个地方；
				let container = $('#tree_box2').find('.vision_tree');
				let scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({
					scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - container.height() * 0.3
				});
			}
		})
	}

	//拉取公司树数据
	load_company() {
		var that = this;
		$('#tree2').jstree({
			"core": {
				'data': function (obj, callback) {
					var jsonstr = "[]";
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({
						type: "GET",
						url: config.BaseURL + url,
						dataType: "json",
						xhrFields: {
							withCredentials: true
						},
						success: function (result) {
							that.companyList = result;
							jsonarray = result;
							callback.call(this, jsonarray);
						}
					});
				},

				"themes": {
					"responsive": true
				},
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
		}).bind("activate_node.jstree", function (e, obj) {
			var currentNode = obj.node; // 获取当前节点
			that.selectedCompanyName2 = currentNode.text;
			that.selectedCompanyId2 = currentNode.id;
			$('#company2').val(currentNode.text).change();
			if ($('#tree_box2').find('.jstree-searchCheck').length > 0) {
				that.selectIndex = '';
				that.selectCount = '';
			}
		})
	}



	//初始化版本号
	initBinSelect2() {
		var that = this;
		$("#binSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			data: this.binData,//为Select添加数据
			templateResult: this.formatRepo
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.binId = data.id;
			that.binName = data.text;
		});
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-file-text-o green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//刷新
	refresh() {
		this.load();
	}
	//打开公司树
	companyClick() {
		$('#tree_box').toggleClass('tree_open');
	}
	initBtn() {
		this.btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_system:runStatus')));
		for (let item of this.btnData) {
			if (item.sourceKey === "system:upgrade" && item.parentId) {
				this.systemUpgrade = true;
			} else if (item.sourceKey === "device:status:delete" && item.parentId) {
				this.hasRowDeletePermission = true;
			} else if (item.sourceKey === 'system:runStatus:SignalTesting') {
				this.isShowSignalTesting = true;
			}
		}
	}
	versionChange(e) {
		this.protocolVersion = e;
		if (this.protocolVersion === '1') {
			this.protocolVersionName = '第一代';
		} else if (this.protocolVersion === '2') {
			this.protocolVersionName = '第二代';
		} else if (this.protocolVersion === '3') {
			this.protocolVersionName = '808协议';
		}
		this.initBin();
	}
	isOnline(val) {
		if (val) {
			this.online = "1";
		} else {
			this.online = "0";
		}
	}
	//清除select2 数据
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//初始化bin数据
	initBin() {
		var that = this;
		return new Promise(function (resolve, reject) {
			let reqdata = 'protocolVersion=' + that.protocolVersion;
			that.jsonApiService.http("system/bininfolist.htiml", reqdata).subscribe(data => {
				var binList = data.data;
				var selectdata = [];
				for (var i = 0; i < binList.length; i++) {
					var obj = {
						id: binList[i].id,
						text: binList[i].binName,
					}
					selectdata[i] = obj;
				}
				that.binData = selectdata;
				var selectObj = $("#binSelect2");
				that.clearSelect2(selectObj);//清除Select中的数据
				selectObj.select2({
					language: "zh-CN",
					data: selectdata,//为Select添加数据
					templateResult: that.formatRepo
				});
				resolve(true);
			})
		})
	}

	setOldVersion(value) {
		this.oldVersion = value
	}

	//升级期望数
	setExpectUpdateNum(value) {
		this.expectUpdateNum = value
	}

	//设备升级
	updata_device() {
		this.selectedRow = false;
		this.checkSelected('设备升级');
		if (this.selectedRow) {
			if (!this.binId) {
				this.jsonApiService.message('请选择设备升级的bin版本号');
				return;
			} else {
				if (!this.runStatus) {
					this.jsonApiService.confirm_message('确认要升级离线设备?').then(() => {
						let reqdata = 'protocolVersion=' + this.protocolVersion + '&deviceId=' + this.deviceId + '&binId=' + this.binId;
						this.jsonApiService.http("system/upgradeoffline.html", reqdata).subscribe(data => {
							this.jsonApiService.message(data.message);
							if (data.success) {
								this.load();
							}
						})
					});
				} else {
					this.jsonApiService.confirm_message('确认要升级设备?').then(() => {
						let reqdata = 'protocolVersion=' + this.protocolVersion + '&deviceId=' + this.deviceId + '&binId=' + this.binId;
						this.jsonApiService.http("system/upgradeonline.html", reqdata).subscribe(data => {
							this.jsonApiService.message(data.message);
							if (data.success) {
								this.load();
							}
						})
					});
				}
			}
		}
	}




	/**
	 * 新的设备升级
	 */

	//分页回调
	firmPaginate(e) {
		this.firmCurPage = e.page + 1;
		this.firmPageSize = e.rows;
		this.loadFirmware();
	}
	// 新版设备升级弹窗
	new_updata_device(modal) {
		if (this.selected.length == 0) {
			this.jsonApiService.message('请选择需要更新设备的车辆');
			this.selectedRow = false;
			return;
		}
		// 选择第一条
		let device;
		for (let item of this.tableData) {
			if (item.isChecked) {
				device = item
				break;
			}
		}
		// 重置公司及分类
		if (device.companyId) {
			// 获取useType的key
			// let useType2 = "";
			// for (let key in this.TcarDeatailUseList) {
			// 	if (this.TcarDeatailUseList[key] == device.useTypeL2 && key == device.useTypeLKey) {
			// 		useType2 = key
			// 	}
			// }
			this.newProtoVersion = '2';
			this.firmcompanyId = device.companyId;
			this.firmuseTypeL2 = device.useTypeLKey;
			this.hardwareVersion = device.hwVersion ? device.hwVersion.split(".")[0] : "";
			this.versionNum = ""

			// 公司和车辆分类回显
			// let companyName = $('#' + device.companyId).find(".jstree-anchor").text()
			$('#company3').find('.tree_company_input').val(device.companyName).change();
			$("#cartypeSelect2").select2("val", [device.useTypeLKey]);
			// 修改子组件里面的信息
			this.companyTreeCarComponent.companyId = device.companyId;
			this.companyTreeCarComponent.companyName = device.companyName;
		} else {
			// 重置
			this.companyTreeCarComponent.resetData()
			this.newProtoVersion = '2';
			this.hardwareVersion = ""
			this.versionNum = ""
		}
		// 重置选择的固件
		this.firmselected = [];
		this.loadFirmware();
		modal.show();
	}
	// 关闭更新设备弹窗
	cancelUpdataDevice(modal) {
		modal.hide();
	}

	// 删除输入
	delKey(type) {
		if (type == "versionNum") {
			this.versionNum = ""
		}
		if (type == "mapSearch") {
			$("#suggestId").val("")
		}
	}
	// 搜索
	firmwareSearch() {
		this.firmCurPage = 1
		this.loadFirmware();
	}
	// 加载固件信息表数据
	loadFirmware() {
		let param = {
			"pageSize": this.firmPageSize,
			"nowPage": this.firmCurPage,
			"parameters": {
				protocolVersion: this.newProtoVersion,		// 协议版本
				companyId: this.firmcompanyId, 			// 公司id
				useTypeL2: this.firmuseTypeL2,			// 车辆用途类型
				hwVersion: this.hardwareVersion,				// 硬件版本
				searchKey: this.versionNum ? this.versionNum.trim() : "",				// 版本号
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("bininfo/list2.html", reqdata).subscribe(data => {
			if (data.exhibitDatas) {
				for (let item of data.exhibitDatas) {
					item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
					item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
				}
				this.firmTableData = data.exhibitDatas;
				this.firmtotalCount = data.recordCount;
			} else {
				this.firmtotalCount = 0;
			}
		})
	}
	//table复选框数据row选中事件回调:处理选中状态和deviceId  复选框上
	firmSelected(row, e, index) {
		// 判断数组中是否有这个索引
		var index = $.inArray(row, this.firmselected);
		if (index === -1) {
			if (this.firmselected.length > 0) {
				// 如果点了另一个就删除上一个
				for (let item of this.firmTableData) {
					item['isChecked'] = false;
				}
				this.firmselected.splice(0, 1);
			}
			row.isChecked = true;
			this.firmselected.push(row);
		} else {
			row.isChecked = false;
			this.firmselected.splice(index, 1);
		}

		this.protocolVersion = row.protocolVersion;
		this.binId = row.binId;
	}
	/**
	 * 单行数据选中事件,仅支持单行选中,不支持多选 用在行上
	 */
	firmRowSelected(row, e, index) {
		if (e.target.className.includes('checkbox') || e.target.className.includes('checkbox-flag') || e.target.className.includes('checkbox-td') || e.target.className.includes('checkbox-label')) {
			this.firmSelected(row, e, index);
			return;
		}
		for (let item of this.firmTableData) {
			item['isChecked'] = false;
		}
		this.firmselected = [];
		row.isChecked = !row.isChecked;
		this.firmselected.push(row);

		this.protocolVersion = row.protocolVersion;
		this.binId = row.binId;
	}
	// 更新设备提交
	updataDeviceSubmit(modal) {
		if (this.firmselected.length == 0) {
			this.jsonApiService.message('请选择一条硬件');
			return;
		}

		if (!this.runStatus) {
			this.jsonApiService.confirm_message('确认要升级离线设备?').then(() => {
				// 这个参数要改成选择的数据的协议版本
				let reqdata = 'protocolVersion=' + this.protocolVersion + '&deviceId=' + this.deviceId + '&binId=' + this.binId;
				this.jsonApiService.http("system/upgradeoffline.html", reqdata).subscribe(data => {
					this.jsonApiService.message(data.message);
					if (data.success) {
						this.cancelUpdataDevice(modal)
						this.loadFirmware();
					}
				})
			});
		} else {
			this.jsonApiService.confirm_message('确认要升级设备?').then(() => {
				let reqdata = 'protocolVersion=' + this.protocolVersion + '&deviceId=' + this.deviceId + '&binId=' + this.binId;
				this.jsonApiService.http("system/upgradeonline.html", reqdata).subscribe(data => {
					this.jsonApiService.message(data.message);
					if (data.success) {
						this.cancelUpdataDevice(modal)
						this.loadFirmware();
					}
				})
			});
		}
	}
	firmRefresh() {
		this.loadFirmware();
	}
	firmcompanySelected(data) {
		this.firmcompanyId = data.companyId;
		this.firmuseTypeL2 = data.useTypeL2;
	}






	//系数标定
	factor(data, result) {
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
			() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					this.initDate();
				});
			}
		);
		this.deviceId = data.deviceId;
	}
	//获取实际重量
	getWeight() {
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		if (this.startTime === undefined || this.startTime === "") {
			this.jsonApiService.message("请选择起始时间");
			return;
		}
		if (this.endTime === undefined || this.endTime === "") {
			this.jsonApiService.message("请选择结束时间");
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime;
		this.jsonApiService.http("weighbridge/weightforreal.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				var text = "";
				var list = data.data;
				for (var i = 0; i < list.length; i++) {
					var weightObject = list[i];
					text = text + weightObject.date.replace(new RegExp("-", "gm"), "").replace(new RegExp(" ", "gm"), "").replace(new RegExp(":", "gm"), "") + "," + weightObject.weight + ";";
					if (i < list.length - 1)
						text += "\n";
				}
				$("#weightForReal").val(text);
			}
		})
	}
	matlabChange() {
		var parameter = $("#parameter").get(0);
		if ($("#modifyParam").is(":checked")) {
			parameter.removeAttribute('disabled');
		} else {
			parameter.setAttribute('disabled', 'disabled');
		}
	}
	//数据格式化
	dataFormat() {
		var weightForReal = $("#weightForReal").val();
		if (this.weightForReal == undefined || this.weightForReal == "") {
			this.jsonApiService.message("无重量数据，搞点数据进来啊！！！");
			return;
		}
		var text = "";
		var textLength = 0;
		var rowData = $.trim(weightForReal).split("\n");
		for (var i = 0; i < rowData.length; i++) {
			var colData = rowData[i].split(/[\t,;/]/);

			var size = colData.length;
			if (colData[size - 1] == "")
				size -= 1;

			for (var j = 0; j < size; j++) {
				if ($.trim(colData[j]).length == 0)
					continue;

				var data = $.trim(colData[j].replace(new RegExp("-", "gm"), "").replace(new RegExp(" ", "gm"), "").replace(new RegExp(":", "gm"), ""));
				if (this.isNumber(data)) {
					text += data;
					if (j == (size - 1)) {
						text += ";"
					} else {
						text += ","
					}
				}
			}
			if ((textLength != text.length) && (i < rowData.length - 1))
				text += "\n";
			textLength = text.length;
		}
		$("#weightForReal").val(text);
	}
	isNumber(val) {
		var regPos = /^\d+(\.\d+)?$/; // 非负浮点数
		var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
		if (regPos.test(val) || regNeg.test(val)) {
			return true;
		} else {
			return false;
		}
	}
	cancelFactorModal(val) {
		val.hide();
		this.weightForReal = "";
	}
	checkParamValue() {
		var flag = true;
		var paramValue = $("#parameter").get(0).value;
		var paramArr = paramValue.split(",");
		if (paramArr.length < 4) {
			this.jsonApiService.message("系数必须为5个,格式如[1000,200,5,2,0]");
			flag = false;
		} else {
			for (var i = 0; i < paramArr.length; i++) {
				if (!this.isNumber(paramArr[i])) {
					this.jsonApiService.message("系数必须为数字,格式如[1000,200,5,2,0]");
					flag = false;
				}
			}
		}
		return flag;
	}
	factorsSubmit(val) {
		this.dataFormat();
		if (!this.checkParamValue()) return;
		var weightForReal = $("#weightForReal").val();
		if (weightForReal == undefined || weightForReal == "") {
			this.jsonApiService.message("无实际重量数据，无法进行标定！！！");
			return;
		}
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		if (this.startTime === undefined || this.startTime === "") {
			this.jsonApiService.message("请选择起始时间");
			return;
		}
		if (this.endTime === undefined || this.endTime === "") {
			this.jsonApiService.message("请选择结束时间");
			return;
		}
		var paramValue = '';
		if ($("#modifyParam").is(":checked")) {
			paramValue = $("#parameter").get(0).value;
		}
		weightForReal = $.trim(weightForReal.replace(new RegExp("\n", "gm"), ""));
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime + '&weightForReal=' + this.weightForReal + '&paramValue=' + paramValue;
		this.jsonApiService.http("system/calibration.htiml", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.factorResult = data.data;
				var result = data.data.split(",");
				// if (result.length == 3) {
				// 	this.Channel_1 = data[0];
				// 	this.Channel_2 = data[1];
				// 	this.Channel_3 = data[2];
				// }
				val.hide();
			}
		})
	}
	isOpenSetChannel() {
		this.autoSetChannelParam = '';
		this.isOpenAutoSetChannel = !this.isOpenAutoSetChannel;
	}
	//自动设置通道系数
	autoSetChannel() {
		this.initChannel()
		let channelParam: any;
		this.autoSetChannelParam = this.autoSetChannelParam.replace('；', ';').replace('，', ',')
		if (this.autoSetChannelParam.indexOf(';') > -1) {
			let getDeviceId = this.autoSetChannelParam.split(';')[0];
			let getChannelParam = this.autoSetChannelParam.split(';')[1];
			this.searchKey = getDeviceId;
			this.load();
			channelParam = getChannelParam ? getChannelParam.split(',') : [];
		} else {
			channelParam = this.autoSetChannelParam ? this.autoSetChannelParam.split(',') : [];
		}
		if (channelParam.length == 0) {
			this.jsonApiService.message('未检索到通道值')
		}
		for (var i = 0; i < channelParam.length; i++) {
			this.channelObj[`channel${i + 1}`] = channelParam[i];
		}
	}
	//channel获取
	getParameter() {
		this.initChannel()
		this.checkSelected('获取');
		if (this.selectedRow) {
			if (this.selected.length === 1) {
				var runStatus = this.selected[0].runStatus;
				if (runStatus == '0') {
					this.jsonApiService.message("设备处于离线状态,获取参数失败!");
					return;
				}

				this.jsonApiService.confirm_message('确认采用 [' + this.protocolVersionName + '] 协议获取该车辆参数吗？').then(() => {
					let reqdata = 'deviceId=' + this.selected[0].deviceId + '&protocolVersion=' + this.protocolVersion;
					if (this.isHex) reqdata += '&isHex=1'
					if (this.moreChannelsChecked) reqdata += '&channelType=32'

					this.jsonApiService.http2("system/getParameter.html", reqdata).subscribe(data => {
						this.jsonApiService.message(data.message);
						if (data.success) {
							var objs = data.paratemet;
							var channels = objs.split(",");
							for (var i = 0; i < channels.length; i++) {
								this.channelObj[`channel${i + 1}`] = channels[i];
							}
						}
					})
				})
			} else {
				this.jsonApiService.message('选取了多条数据,请选取一条数据获取')
			}
		}
	}
	//重置传感器
	resetSensor(val) {
		this.checkSelectedRow('请选择一条数据进行传感器重置');
		if (this.selectedRow) {
			val.show();
		}
	}
	cancelResetSensor(val) {
		this.resetSensorType = '';
		val.hide();
	}
	//重置传感器类型change
	resetSensorChange(val) {
		this.resetSensorType = val;
	}
	resetSensorSubmit(val) {
		if (!this.resetSensorType) {
			this.jsonApiService.message('重置原因不能为空');
			return;
		}
		let reqdata = 'deviceId=' + this.selected[0].deviceId + '&logType=' + this.resetSensorType;
		this.jsonApiService.http2("sensormonitor/resetForSensorInfo.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.load();
				this.resetSensorType = '';
				val.hide();
			}
		})
	}
	self_confirm_message(message) {
		return new Promise(function (resolve, reject) {
			this.notificationService.smartMessageBox({
				title: "提示",
				content: message,
				buttons: '[确认][取消][保存系数设置队列]'
			}, (ButtonPressed) => {
				if (ButtonPressed === "确认") {
					resolve(1);
				}
				if (ButtonPressed === "保存系数设置队列") {
					resolve(2);
				}
				if (ButtonPressed === "取消") {
					this.notificationService.smallBox({
						content: "操作取消",
						timeout: 3000
					});
					return;
				}

			});
		}.bind(this))
	}
	//channel更新
	remoteTuning() {
		this.checkSelected('更新');
		if (this.selectedRow) {
			if (this.selected.length === 1) {
				var online = "online";
				var runStatus = this.selected[0].runStatus;
				if (runStatus == '0') {
					online = "offline";
				}

				this.self_confirm_message('确认采用 [' + this.protocolVersionName + '] 协议更新该车辆参数吗？').then((SaveType) => {
					let isVerify = false;
					for (let i = 1; i < 9; i++) {
						if (this.channelObj[`channel${i}`]) isVerify = true
					}

					if (!isVerify) {
						this.jsonApiService.message("参数不能为空!");
						return;
					}

					let apiUrl;
					if (SaveType == 1) {
						apiUrl = "system/remotetuning.html";
					} else if (SaveType == 2) {
						apiUrl = 'deviceCoefHandler/addDeviceCoefHandler.html';
					}

					const reqdata = {
						online,
						deviceId: this.selected[0].deviceId,
						protocolVersion: this.protocolVersion,
						isHex: this.isHex ? 1 : 0,
						channelType: this.moreChannelsChecked ? 32 : null,
						...this.channelObj
					}

					this.jsonApiService.http_obj(apiUrl, this.filterObject(reqdata), false).subscribe(data => {
						this.jsonApiService.message(data.message);
						if (data.success && SaveType == 1) {
							var objs = data.paratemet;
							if (objs != undefined || objs != null) {
								var channels = objs.split(",");
								for (var i = 0; i < channels.length; i++) {
									this.channelObj[`channel${i + 1}`] = channels[i];
								}
							}
						}
					})
				})
			} else {
				this.jsonApiService.message('选取了多条数据,请选取一条数据获取')
			}
		}
	}
	// 过滤空值
	filterObject(obj: Record<string, any>): Record<string, any> {
		return (
			Object.keys(obj)
				// 过滤空值
				.filter(key => obj[key] === 0 || Boolean(obj[key]))
				// 组装新对象
				.reduce((prev: Record<string, any>, current: string) => {
					prev[current] = obj[current]
					return prev
				}, {})
		)
	}
	//时间转化
	getTime(date) {
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
		return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
	}
	//初始化时间插件
	initDate() {
		$("#datetimepicker1").datetimepicker({// 时间插件
			format: "yyyy-mm-dd hh:ii:ss",
			language: "zh-CN",
			autoclose: true,
			todayHighlight: true
		}).on("changeDate", function (e) {
			var date = e.date;
			var time = this.getTime(date);
			$("#datetimepicker2").datetimepicker("setStartDate", time);
		});

		$("#datetimepicker2").datetimepicker({// 时间插件
			format: "yyyy-mm-dd hh:ii:ss",
			language: "zh-CN",
			autoclose: true,
			todayHighlight: true
		}).on("changeDate", function (e) {
			var date = e.date;
			var time = this.getTime(date);
			$("#datetimepicker1").datetimepicker("setEndDate", time);
		});

		var date = new Date();
		$("#datetimepicker2").val(this.getTime(date));// 当前时间
		date.setDate(date.getDate() - 7);// 设置前一天
		$("#datetimepicker1").val(this.getTime(date));
	}
	//重量修正
	weightFixBtn(val) {
		if (this.protocolVersion === '3') {
			this.jsonApiService.message('重量修正目前仅支持第一代和第二代协议');
			return;
		}
		this.selectedRow = false;
		this.checkSelectedRow('请选择一条数据进行重量修正');
		if (this.selectedRow) {
			val.show();
			this.weightFix.isRectify = this.selected[0].rectify;
			this.weightFix.typeRectify = this.selected[0].typeRectify ? this.selected[0].typeRectify + '' : '1';
			this.weightFix.factorRectify = this.selected[0].factorRectify == undefined ? "1" : this.selected[0].factorRectify == 0 ? "1" : this.selected[0].factorRectify;
		} else {
			this.weightFix.isRectify = false;
			this.weightFix.typeRectify = '1';
			this.weightFix.factorRectify = '1';
		}
		//请求下发数据
		this.weightFix.lastDate = '';
		this.weightFix.status = 0  //默认为0
		this.getIssueData()
	}
	cancelWeightFix(val) {
		val.hide();
	}
	//重量修正提交
	weightFixSubmit(val) {
		if (!this.weightFix.factorRectify || this.weightFix.factorRectify === '0') {
			this.jsonApiService.message("请输入倍数或倍数不允许为0");
			return;
		}
		this.jsonApiService.confirm_message("确认是否需要修正该设备重量数值？").then(() => {
			let reqdata = '&deviceId=' + this.selected[0].deviceId + '&isRectify=' + this.weightFix.isRectify + '&factorRectify=' + this.weightFix.factorRectify + '&typeRectify=' + this.weightFix.typeRectify;
			this.jsonApiService.http("system/weightmodify.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					val.hide();
					this.load();
					this.selectedRow = false;
				}
			})
		})
	}
	//重置设备编码
	resetOrder(val) {
		if (this.protocolVersion === '3') {
			this.jsonApiService.message('重置设备编码目前仅支持第一代和第二代协议');
			return;
		}
		this.selectedRow = false;
		this.checkSelectedRow('请选择在线未绑定车牌车辆进行设备编码重置');
		if (this.selectedRow) {
			if (this.selected[0].runStatus === '0') {
				this.jsonApiService.message('请选择在线车辆进行设备编码重置');
				return;
			} else {
				if (this.selected[0].carNumber) {
					this.jsonApiService.message('该设备编号已绑定车辆，不允许使用!');
					return;
				} else {
					this.carNumber = '';
					this.carDeviceId = '';
					this.clearSelect2($("#resetCarNumberSelect2"));//清除Select中的数据
					this.deviceInfoTableData = [];
					val.show()
				}
			}
		}
	}
	selectCompany() {
		var that = this;
		$("#resetCarNumberSelect2").select2({
			language: "zh-CN",
			placeholder: "请输入...",
			allowClear: true,
			minimumInputLength: 2,      //最少2个字符，select2才显示查询的内容
			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: {
					withCredentials: true
				},
				data: function (params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function (data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if (data.data.length <= 10) {
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if (arr.indexOf(car.carNumber) != -1) {
								sameCar.push(car.carNumber)
							} else {
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function (index, car) {
							if (sameCar.indexOf(car.carNumber) != -1) {
								options.push({
									id: car.deviceId,
									text: car.carNumber + "[" + car.parentName + "]"
								})
							} else {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					} else {
						$(data.data).each(function (index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options    //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.carFormatRepo
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.carDeviceId = data.id;
			if (data.text.indexOf('[') > 0) {
				that.carNumber = data.text.split('[')[0];
			} else {
				that.carNumber = data.text;
			}
			that.getDeviceInfoByCarNumber();
		});
	}
	//select2 格式回调函数
	carFormatRepo(state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	deviceInfoTableData: any = [];
	//根据车牌号码获取设备信息,主要处理一个车牌对应多个设备ID情况下,设备重置问题
	getDeviceInfoByCarNumber() {
		this.deviceInfoTableData = [];
		this.jsonApiService.http_obj("system/getRestInfoByCarNumber.html", { carNumber: this.carNumber }).subscribe(data => {
			if (data.success) {
				this.deviceInfoTableData = data.data;
				if (!this.deviceInfoTableData) return;
				for (let item of this.deviceInfoTableData) {
					if (JSON.stringify(item.markCombination) == '{}') {
						item.isEnterFactory = true
					} else {
						if (item.markCombination.fakeOnline == 1) {
							item.isEnterFactory = false
						} else {
							item.isEnterFactory = true
						}
					}
				}
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//重置设备编码提交
	deviceReset(val, row) {
		if (row.deviceId && this.carNumber) {
			let reqdata = '&deviceId=' + row.deviceId + '&carNumber=' + row.carNumber + '&newDeviceId=' + this.selected[0].deviceId;
			this.jsonApiService.http("system/uploaddeviceid.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					val.hide();
					this.load();
					this.selectedRow = false;
					this.carNumber = '';
					this.carDeviceId = '';
					this.deviceInfoTableData = [];
					this.clearSelect2($("#resetCarNumberSelect2"));//清除Select中的数据
				}
			})
		} else {
			this.jsonApiService.message('车牌号码不能为空')
		}
	}
	cancelDeviceReset(val) {
		this.carNumber = '';
		this.carDeviceId = '';
		this.clearSelect2($("#resetCarNumberSelect2"));//清除Select中的数据
		val.hide();
		this.deviceInfoTableData = [];
	}
	//自动清零复选框change事件
	resetChange(checked, type) {
		if (type === 'Y' && checked) {
			this.isAuto = true;
		} else if (type === 'N' && checked) {
			this.isAuto = false;
		}
	}
	//清零change事件
	zeroChange(checked, type) {
		if (type === 'Y' && checked) {
			this.isZero = true;
		} else if (type === 'N' && checked) {
			this.isZero = false;
		}
	}
	//清零btn事件
	resetZero(val) {
		if (this.protocolVersion === '3') {
			this.jsonApiService.message('远程清零目前仅支持第一代和第二代协议');
			return;
		}
		this.selectedRow = false;
		this.checkSelected('远程清零');
		if (this.selectedRow) {
			val.show()
		}
	}
	//自动清零提交
	autoReset(val) {
		this.checkSelected('自动清零');
		if (this.selectedRow) {
			let reqdata = '&deviceId=' + this.deviceId + '&isAuto=' + this.isAuto;
			this.jsonApiService.http("system/autoreset.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					val.hide();
					this.load();
					this.selectedRow = false;
				}
			})
		}
	}
	//清零提交
	remoteReset(val) {
		this.checkSelected('清零');
		if (this.selectedRow) {
			let reqdata = 'protocolVersion=' + this.protocolVersion + '&deviceId=' + this.deviceId + '&isAuto=' + this.isAuto;
			this.jsonApiService.http("system/remotereset.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					val.hide();
					this.load();
					this.selectedRow = false;
				}
			})
		}
	}
	//表格搜索
	table_search() {
		this.curPage = 1;
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据[主table表]
	isShowBattery: boolean = false; //是否显示电池
	load() {
		this.allChecked = false;
		this.selected = [];
		this.runStatus = true;
		let tableSearch = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: this.searchKey,
				company: this.selectedCompanyId,
				online: this.online,
				sort: this.sortType,
				filterType: this.filterType,
				useTypeL2: $('#TcarTypeSelect2').val() ? $('#TcarTypeSelect2').val() : '',
				useTypeL1: $('#TcarTypeSelect2').val() ? $('#TcarTypeSelect2').val().slice(0, 2) : ''
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(tableSearch);
		this.jsonApiService.http("system/realTimeData.html", reqdata).subscribe(data => {
			if (data.exhibitDatas) {
				for (let item of data.exhibitDatas) {
					let carUploadDate = item.carUploadDate;
					let gpsUploadDate = item.gpsUploadDate;
					if (carUploadDate && gpsUploadDate) {
						let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate));
						abs >= 30 * 60 * 1000 ? item.isShowGPSAlert = true : item.isShowGPSAlert = false;//计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
					}
					item.useTypeLKey = item.useTypeL2;//车辆类型转换为中文
					item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);//车辆类型转换为中文
					item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);//车辆类型转换为中文

					item['isChecked'] = false;
					if (item.sensorChannel && item.sensorChannel.length > 0) {
						let temArr: any = [];
						for (var j = 0; j < item.sensorChannel.length; j++) {
							let obj = {
								value: item.sensorChannel[j],
								flag: false,
							}
							if (item.coef) {
								if (item.coef[+item.sensorChannel[j] - 1]) {
									obj.flag = true;
								}
							}
							temArr.push(obj);
						}
						item.sensorChannelT = temArr;
					}
					if (item.coef) {
						let coefArr = [];
						for (let i = 0; i < item.coef.length; i++) {
							let _item = item.coef[i];
							if (_item) {
								var obj = {
									value: item.coef[i],
									index: i + 1
								}
								coefArr.push(obj);
							}
						}
						item.coef = coefArr;
					} else {
						item.coef = [];
					}

					if (JSON.stringify(item.markCombination) == '{}') {
						item.isEnterFactory = true
					} else {
						if (item.markCombination.fakeOnline == 1) {
							item.isEnterFactory = false
						} else {
							item.isEnterFactory = true
						}

					}

					//显示电池容量
					if (item.batteryPer == 0 || item.batteryPer == 100 || item.batteryPer > 100) {
						item.isShowBattery = false
					} else {
						item.isShowBattery = true;
						item.BatteryHeight = Math.round((16 * item.batteryPer) / 100)
					}
				}
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//根据编码映射对应车辆类型名称
	getUseTypeNameL1(key) {
		if (key) {
			return this.TcarUseList[key];
		} else {
			return '';
		}
	}
	//根据编码映射对应车辆类型名称
	getUseTypeNameL2(key) {
		if (key) {
			return this.TcarDeatailUseList[key];
		} else {
			return '';
		}
	}
	//排序change事件
	sortChange() {
		this.load();
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//table 全部选中
	allSelected() {
		this.allChecked = !this.allChecked;
		if (!this.allChecked) {
			for (let item of this.tableData) {
				item['isChecked'] = false;
			}
			this.selected = [];
			this.deviceId = '';
		} else {
			var temArr = [];
			for (let item of this.tableData) {
				item['isChecked'] = true;
				temArr.push(item.deviceId);
				this.selected.push(item);
			}
			for (let item of this.selected) {
				temArr.push(item.deviceId);
				if (item.runStatus === '0') {
					this.runStatus = false;
				}
			}
			this.deviceId = temArr.join(',');
		}
	}
	//table复选框数据row选中事件回调:处理选中状态和deviceId
	rowSelected(row, e, index) {
		var index = $.inArray(row, this.selected);
		if (index === -1) {
			row.isChecked = true;
			this.selected.push(row);
		} else {
			row.isChecked = false;
			this.selected.splice(index, 1);
		}
		var temArr = [];
		for (let item of this.selected) {
			temArr.push(item.deviceId);
			if (item.runStatus === '0') { //判断选中数据中是否存在离线车辆
				this.runStatus = false;
			}
		}
		this.deviceId = temArr.join(','); //处理deviceId,与后台接口交互参数
		this.selected.length === this.pageSize ? this.allChecked = true : this.allChecked = false; //判断是否全选状态
	}
	/**
	 * 单行数据选中事件,仅支持单行选中,不支持多选
	 */
	singleRowSelected(row, e, index) {
		if (e.target.className.includes('checkbox') || e.target.className.includes('checkbox-flag') || e.target.className.includes('checkbox-td') || e.target.className.includes('checkbox-label')) {
			this.rowSelected(row, e, index);
			return;
		}
		for (let item of this.tableData) {
			item['isChecked'] = false;
		}
		this.selected = [];
		this.runStatus = true;
		row.isChecked = !row.isChecked;
		this.selected.push(row);
		if (row.runStatus === '0') {
			this.runStatus = false;
		}
		this.deviceId = row.deviceId;
	}
	//验证是否选择了数据
	checkSelected(type) {
		if (this.selected.length == 0) {
			this.jsonApiService.message('请选择需要' + type + '的数据');
			this.selectedRow = false;
			return;
		} else {
			this.selectedRow = true;
		}
	}
	//验证是否选择了数据(单行数据)
	checkSelectedRow(val) {
		if (this.selected.length == 0) {
			this.selectedRow = false;
			this.jsonApiService.message(val);
			return;
		} else {
			if (this.selected.length == 1) {
				this.selectedRow = true;
			} else {
				this.jsonApiService.message('你选择多条数据,请选择单行数据操作');
				this.selectedRow = false;
				return;
			}
		}
	}
	//关闭参数配置弹窗
	cancelparamConfig(val) {
		val.hide();
		for (var item in this.config) {
			if (item === 'params') {
				for (var lis in this.config.params) {
					this.config.params[lis] = '';
				}
			} else {
				this.config[item] = '';
			}
		}
	}
	//参数配置
	paramConfig(val) {
		if (this.protocolVersion === '1') {
			this.jsonApiService.message('目前只支持808协议的参数配置,请选择808协议');
			return;
		}
		this.selectedRow = false;
		this.checkSelectedRow('请选择一条数据进行参数配置');
		if (this.selectedRow) {
			$("#serviceTime").val('')
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				() => {
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(
						() => { common.initDatePicker("#serviceTime", 0) }
					)
				}
			);
			val.show();
		}
	}

	//高级功能
	advancedFnBtn(val) {
		val.show();
	}
	//关闭高级功能弹窗
	closeAdvancedFn(val) {
		val.hide();
	}

	// ------------ 设置频率 start ---------- //
	setFrequencyCurPage: number = 1  // 当前页码
	setFrequencyPageSize: number = 10 // 页的条数
	setFrequencytotalCount: number = 0 // 分页总条数
	setFrequencyTableData = []

	setFrequencyBtn(val) {
		this.loadSetFrequency()
		val.show();
	}
	cancelSetFrequency(val) {
		val.hide();
	}

	// 表单刷新
	setFrequencyTableRefresh() {
		this.loadSetFrequency();
	}
	//分页回调
	setFrequencyPaginate(e) {
		this.setFrequencyCurPage = e.page + 1;
		this.setFrequencyPageSize = e.rows;
		this.loadSetFrequency();
	}
	// 加载厂区表数据
	loadSetFrequency() {
		let param = {
			"pageSize": this.setFrequencyPageSize,
			"nowPage": this.setFrequencyCurPage,
			"parameters": {}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("cancelAutoRateSetting/pageCancelAutoRateSetting.html", reqdata).subscribe(data => {
			this.setFrequencyTableData = data.exhibitDatas;
			this.setFrequencytotalCount = data.recordCount;
		})
	}

	// 添加厂区的实体对象
	setFrequency: any = {
		id: '',
		carNumber: '',
		deviceId: '',
		days: ''
	}
	isMore = false
	// 添加厂区弹窗
	setFrequencyAdd(modal, isMore) {
		if (isMore === 'more') {
			this.isMore = true
		} else {
			this.isMore = false
		}

		this.setFrequency = {
			id: '',
			carNumber: '',
			deviceId: '',
			days: ''
		}
		var str = str = $("<span style='color:#CCCCCC'>请选择车辆</span>")
		$('#setFrequencySelect2').val("");
		$("#select2-setFrequencySelect2-container").empty();
		$("#select2-setFrequencySelect2-container").attr("title", "");
		$("#select2-setFrequencySelect2-container").prepend(str);
		modal.show();
	}

	// 编辑厂区弹窗
	editSetFrequency(row, modal) {
		this.isMore = false
		this.setFrequency = JSON.parse(JSON.stringify(row));

		var str = $("<span class='select2-selection__rendered'>" + this.setFrequency.carNumber + "</span>");
		$('#setFrequencySelect2').val(this.setFrequency.carNumber);
		$("#select2-setFrequencySelect2-container").empty();
		$("#select2-setFrequencySelect2-container").attr("title", "");
		$("#select2-setFrequencySelect2-container").prepend(str);
		modal.show();
	}

	//初始化车辆
	initCar() {
		var that = this;
		$("#setFrequencySelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			minimumInputLength: 2,      //最少2个字符，select2才显示查询的内容
			ajax: {
				url: config.BaseURL + "stats/carListByCarNumber.html",
				dataType: 'json',
				delay: 50,
				method: "POST",
				xhrFields: { withCredentials: true },
				data: function (params) {
					return {
						"carNumber": params.term // search term
					};
				},
				processResults: function (data, params) {
					var options = new Array();
					// 小于10个数量才判断重复
					if (data.data.length <= 10) {
						let arr = []
						let sameCar = []
						// 判断相同的车牌号
						for (let index = 0; index < data.data.length; index++) {
							let car = data.data[index];
							if (arr.indexOf(car.carNumber) != -1) {
								sameCar.push(car.carNumber)
							} else {
								arr.push(car.carNumber);
							}
						}
						$(data.data).each(function (index, car) {
							if (sameCar.indexOf(car.carNumber) != -1) {
								options.push({
									id: car.deviceId,
									text: car.carNumber + "[" + car.parentName + "]"
								})
							} else {
								options.push({
									id: car.deviceId,
									text: car.carNumber
								})
							}
						});
					} else {
						$(data.data).each(function (index, car) {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						});
					}
					return {
						results: options //获取查询后的结果
					};
				},
				cache: true
			},
			templateResult: this.formatRepo
		}).on("select2:select", function (e) {
			var data = e.params.data;
			that.setFrequency.deviceId = data.id;
			if (data.text.indexOf('[') > 0) {
				that.setFrequency.carNumber = data.text.split('[')[0];
			} else {
				that.setFrequency.carNumber = data.text;
			}
		});
	}

	// 关闭弹框
	closeSetFrequency(modal) {
		$("#setFrequencyFrom").data('bootstrapValidator').resetForm();
		modal.hide();
	}

	// 添加提交
	addSubmitSetFrequency(modal) {
		console.log(this.setFrequency);
		const data = { ...this.setFrequency }

		if (!data.deviceId) {
			this.jsonApiService.message('请输入设备编号');
			return
		}

		if (parseInt(data.days) > 365) {
			this.jsonApiService.message('取消时长不能大于365天')
			return
		}

		if (this.isMore) {
			data.deviceId = data.deviceId
				.split(/[，,\n]/)
				.filter(item => item)
				.join(',')
		}

		const url = this.isMore ? 'cancelAutoRateSetting/addMoreCancelAutoRateSetting.html' : 'cancelAutoRateSetting/addCancelAutoRateSetting.html'
		this.jsonApiService.http_obj(url, data).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.loadSetFrequency();
				this.closeSetFrequency(modal)
			}
		})
	}
	// 编辑提交
	editSubmitSetFrequency(modal) {
		$('#setFrequencyFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#setFrequencyFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.jsonApiService.http_obj("cancelAutoRateSetting/editCancelAutoRateSetting.html", this.setFrequency).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.loadSetFrequency();
					this.closeSetFrequency(modal)
				}
			})
		}
	}
	// 取消自动频率设置，全部删除
	frequencyDeleteAll(){
		// /cancelAutoRateSetting/delAllCancelAutoRateSetting.html
		this.jsonApiService.confirm_message('此操作将删除所有记录,确认要删除').then(() => {
			this.jsonApiService.http("cancelAutoRateSetting/delAllCancelAutoRateSetting.html",'').subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.loadSetFrequency();
				}
			})
		})
	}

	// 删除厂区
	delSetFrequency(row) {
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("cancelAutoRateSetting/delCancelAutoRateSetting.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.loadSetFrequency();
				}
			})
		})
	}
	// ----------------- 设置频率 end ----------------//

	//读取设备编号
	outputDeviceId() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadDeviceId.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.config.deviceId = data.data;
			}
		})
	}
	//写设备编号
	inputDeviceId() {
		if (!this.config.deviceId) {
			this.jsonApiService.message('设备编号不能为空');
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion + '&writeDeviceId=' + this.config.deviceId;
		this.jsonApiService.http2("devicemanage/sendCodeForWriteDeviceId.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})
	}
	//读取设备状态数据
	outputDeviceStatue() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadDeviceStatus.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.vcd = temData[0] ? temData[0] : '';
					this.config.ioStatusOne = temData[1] ? temData[1] : '';
					this.config.ioStatusTwo = temData[2] ? temData[2] : '';
					this.config.ioStatusThree = temData[3] ? temData[3] : '';
					this.config.ACCSignal = temData[4] ? temData[4] : '';
				}
			}
		})
	}
	//读取当前重量
	outputWeight() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadWeight.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.config.weight = data.data;
			}
		})
	}
	//读取上传频率
	outputUpload() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadTimePeriod.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.config.upload = data.data;
			}
		})
	}
	//写上传频率
	inputUpload() {
		if (!this.config.upload) {
			this.jsonApiService.message('上传频率不能为空');
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion + '&time=' + this.config.upload;
		this.jsonApiService.http2("devicemanage/sendCodeForWriteTimePeriod.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})
	}
	//读取设备版本
	outputDeviceVersion() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadDeviceVersion.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.binVersion = temData[0] ? temData[0] : '';
					this.config.algorithmVersion = temData[1] ? temData[1] : '';
					this.config.bootLoaderVersion = temData[2] ? temData[2] : '';
				}
			}
		})
	}
	//读GSM
	outputGSM() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadGsm.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.ICCId = temData[1] ? temData[1] : '';
					this.config.GSMstrength = temData[0] ? temData[0] : '';
				}
			}
		})
	}
	//读取GPS
	outputGPS() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadGps.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.longitude = temData[0] ? temData[0] : '';
					this.config.latitude = temData[1] ? temData[1] : '';
					this.config.speed = temData[2] ? temData[2] : '';
					this.config.azimuth = temData[3] ? temData[3] : '';
					this.config.satellites = temData[4] ? temData[4] : '';
					this.config.GPSstrength = temData[5] ? temData[5] : '';
				}
			}
		})
	}
	//读IP
	outputIP() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadIp.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.Ip = temData[0] ? temData[0] : '';
					this.config.port = temData[1] ? temData[1] : '';
				}
			}
		})
	}
	//写IP
	inputIP() {
		var isValidIP = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
		if (!this.config.Ip) {
			this.jsonApiService.message('ip地址不能为空');
			return;
		} else {
			if (!isValidIP.test(this.config.Ip)) {
				this.jsonApiService.message('ip地址格式不正确');
				return;
			}
		}
		var isValidPort = /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
		if (!this.config.port) {
			this.jsonApiService.message('端口号不能为空');
			return;
		} else {
			if (!isValidPort.test(this.config.port)) {
				this.jsonApiService.message('端口号格式不正确');
				return;
			}
		}
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion + '&ip=' + this.config.Ip + '&port=' + this.config.port;
		this.jsonApiService.http2("devicemanage/sendCodeForWriteIp.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})
	}
	//读取算法参数
	outputParams() {
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
		this.jsonApiService.http2("devicemanage/sendCodeForReadAlgorithmParamter.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				let temData = data.data.split(',');
				if (temData) {
					this.config.params.channel1 = temData[0] ? temData[0] : '';
					this.config.params.channel2 = temData[1] ? temData[1] : '';
					this.config.params.channel3 = temData[2] ? temData[2] : '';
					this.config.params.channel4 = temData[3] ? temData[3] : '';
					this.config.params.channel5 = temData[4] ? temData[4] : '';
					this.config.params.channel6 = temData[5] ? temData[5] : '';
					this.config.params.channel7 = temData[6] ? temData[6] : '';
					this.config.params.channel8 = temData[7] ? temData[7] : '';
					this.config.params.channel9 = temData[8] ? temData[8] : '';
					this.config.params.channel10 = temData[9] ? temData[9] : '';
					this.config.params.channel11 = temData[10] ? temData[10] : '';
					this.config.params.channel12 = temData[11] ? temData[11] : '';
					this.config.params.channel13 = temData[12] ? temData[12] : '';
					this.config.params.channel14 = temData[13] ? temData[13] : '';
					this.config.params.channel15 = temData[14] ? temData[14] : '';
					this.config.params.channel16 = temData[15] ? temData[15] : '';
					//					for(var i = 0; i < temData.length; i++){
					//						this.config.params.channel+i = temData[i]?temData[i]:''
					//					}
				}
			}
		})
	}
	//写算法参数
	inputParams() {
		var newData = '';
		var isTRUE = false;
		for (var item in this.config.params) {
			if (this.config.params[item]) {
				isTRUE = true;
				break;
			}
		}
		if (!isTRUE) { this.jsonApiService.message('通道至少有一个值'); return; };
		for (let k in this.config.params) {
			if (this.config.params.hasOwnProperty(k) === true) {
				newData += encodeURIComponent(k) + '=' + encodeURIComponent(this.config.params[k]) + '&';
			}
		}
		let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion + '&' + newData;
		this.jsonApiService.http2("devicemanage/sendCodeForWriteAlgorithmParamter.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})
	}
	//读服务到期
	outputServiceTime() {
		let reqdata = 'deviceId=' + this.deviceId + '&type=1';
		this.jsonApiService.http2("logForDeviceEndServiceTime/issuedInstruct.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.config.serviceTime = data.data;
			}
		})
	}
	//写服务到期
	inputServiceTime() {
		this.config.serviceTime = $("#serviceTime").val();
		console.log(this.config.serviceTime)
		if (!this.config.serviceTime) {
			this.jsonApiService.message('服务到期日期不能为空');
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&type=2' + '&serviceTime=' + this.config.serviceTime;
		this.jsonApiService.http2("logForDeviceEndServiceTime/issuedInstruct.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})
	}


	//恢复出厂设置&重启设备终端&算法清零
	paramsOperation(type, mes) {
		this.jsonApiService.confirm_message('确认要进行' + mes + '?').then(() => {
			let reqdata = 'deviceId=' + this.deviceId + '&protocolVersion=' + this.protocolVersion;
			let Url = "devicemanage/" + type + ".html";
			this.jsonApiService.http2(Url, reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
			})
		})

	}
	//重置算法执行起点按钮回调
	resetMatlabStart(val) {
		this.selectedRow = false;
		this.checkSelectedRow('请选择一条数据进行算法重置');
		if (this.selectedRow) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				() => {
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(
						() => { common.initDatePicker("#resetStartTime", 0) }
					)
				}
			);
			val.show();
		}
	}
	//重置算法执行起点取消
	cancelMatlabReset(val) {
		val.hide();
		$("#resetStartTime").val('');
		this.resetMatlabStartTime = '';
	}
	//重置算法执行起点提交
	matlabReset(val) {
		this.resetMatlabStartTime = $("#resetStartTime").val();
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.resetMatlabStartTime;
		this.jsonApiService.http("system/resetMatlabJobStartTime.htiml", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			this.cancelMatlabReset(val);
		})
	}
	//删除
	del_car_running(data) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + data.id;
			this.jsonApiService.http("system/deleteById.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
			})
		})
	}

	/**
	 * 批量上传模块功能
	 */

	mulUpload: any = {
		selectedCompanyName: '',
		selectedCompanyId: '',
		useTypeL1: '',
		useTypeL2: '',
		carUseTpyeText: '',
		upload: '',
		time: ''
	}
	//批量设置上传频率
	mulConfigUpload(modal) {
		if (!this.protocolVersion) {
			this.jsonApiService.message('请选择设备版本号');
			return;
		}
		//清空数据
		this.mulUploadTap = '1';
		this.mulUpload.selectedCompanyName = '';
		this.mulUpload.selectedCompanyId = '';
		$('#ULcompany').val("");
		this.mulUpload.useTypeL1 = '';
		this.mulUpload.useTypeL2 = '';
		this.mulUpload.time = '';
		var str = $("<span class='select2-selection__placeholder'>全部</span>");
		$("#select2-ULcarTypeSelect2-container").empty();
		$("#select2-ULcarTypeSelect2-container").attr("title", "全部");
		$("#select2-ULcarTypeSelect2-container").prepend(str);
		$('#ULcarTypeSelect2').val('');
		this.mulUpload.carUseTpyeText = '';
		$('#uploadSelect2').val('');
		this.is1sFrequency = '0';
		$("#mulUploadFrom").data('bootstrapValidator').resetForm();

		modal.show();
		this.getUploadDate();
		this.ULGetCompanyTree();
		var UL_tree_box = document.getElementById('UL_tree_box');
		var ULcompany = document.getElementById('ULcompany');
		//公司树弹窗显示隐藏交互事件
		var html = document.getElementsByTagName('html')[0];
		html.onclick = function (e: any) {
			if (!(e.target === ULcompany || e.target.className === 'jstree-node  jstree-open' || e.target.className === 's_company_root_box' || e.target.className === 'treeSearchInputBox' || e.target.className === 'treeSearchInput' || e.target.className === 'jstree-children' || e.target.className === 's_del_icon' || e.target.className === 'jstree-node  jstree-leaf' || e.target.className === 'jstree-icon jstree-ocl' || e.target.className === 'vision_tree' || e.target.className === 'jstree-node jstree-leaf jstree-closed')) {
				UL_tree_box.className = UL_tree_box.className.replace("tree_open", "");
			}
		}
	}
	//上传频率下拉数据
	getUploadDate() {
		let that = this, upLoadList: any = [];
		for (var i = 1; i <= 60; i++) {
			var temObj = {
				id: i,
				text: i
			}
			upLoadList.push(temObj)
		}
		$("#uploadSelect2").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			data: upLoadList,//为Select添加数据
			templateResult: this.formatRepo
		})
	}
	//批量上传关闭
	FromCancelUpload(modal) {
		modal.hide();
	}
	FromUploadSubmit(modal1, modal2) {

		this.mulUpload.useTypeL1 = $('#ULcarTypeSelect2').val().slice(0, 2);
		this.mulUpload.useTypeL2 = $('#ULcarTypeSelect2').val();
		this.mulUpload.time = $('#uploadSelect2').val();
		$('#mulUploadFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#mulUploadFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			if (this.mulUploadTap == '1') {
				if (this.mulUpload.time == '') {
					this.jsonApiService.message("上传频率为必填项");
					return;
				}
				modal1.show();
				this.mulUpload.carUseTpyeText = this.getArrLable($('#ULcarTypeSelect2').val())
			} else if (this.mulUploadTap == '2') {
				//批量读取硬件版本号
				let reqdata = 'companyId=' + this.mulUpload.selectedCompanyId + '&useTypeL2=' + this.mulUpload.useTypeL2 + '&protocolVersion=' + this.protocolVersion;
				this.jsonApiService.http("system/setVersionForBatch.html", reqdata).subscribe(data => {
					this.jsonApiService.message(data.message);
					modal2.hide();
				})
			}
			else if (this.mulUploadTap == '3') {
				//批量读取ICCID
				let reqdata = 'companyId=' + this.mulUpload.selectedCompanyId + '&useTypeL2=' + this.mulUpload.useTypeL2 + '&protocolVersion=' + this.protocolVersion;
				this.jsonApiService.http("system/setICCIDForBatch.html", reqdata).subscribe(data => {
					this.jsonApiService.message(data.message);
					modal2.hide();
				})
			}

		}
	}
	//批量上传提交
	uploadSubmit(modal) {
		let reqdata = 'companyId=' + this.mulUpload.selectedCompanyId + '&useTypeL2=' + this.mulUpload.useTypeL2 + '&protocolVersion=' + this.protocolVersion + '&time=' + this.mulUpload.time + '&filter=' + this.is1sFrequency;
		this.jsonApiService.http("system/settimeperiodforbatch.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			modal.hide();
		})
	}
	cancelUpload(modal) {
		modal.hide();
	}
	/**
	 *批量上传模块公司树处理
	 */
	ULGetCompanyTree() {
		var that = this;
		$('#ULtree').jstree({
			"core": {
				'data': function (obj, callback) {
					var jsonstr = "[]";
					var jsonarray = eval('(' + jsonstr + ')');
					var url = 'company/companytree.html';
					$.ajax({
						type: "POST",
						url: config.BaseURL + url,
						dataType: "json",
						xhrFields: { withCredentials: true },
						success: function (result) {
							jsonarray = result;
							callback.call(this, jsonarray);
						}
					});
				},
				"themes": { "responsive": true },
				"multiple": false,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"plugins": ["search"]
		}).bind("activate_node.jstree", function (e, obj) {
			var currentNode = obj.node; // 获取当前节点
			that.mulUpload.selectedCompanyName = currentNode.text;
			that.mulUpload.selectedCompanyId = currentNode.id;
			$('#ULcompany').val(currentNode.text).change();
			that.ULcompanySearch();
		})
	}
	//打开公司树
	ULcompanyClick() {
		$('#UL_tree_box').toggleClass('tree_open');
	}
	//公司树搜索
	ULcompanySearch() {
		var value = $('#ULtreeSearchInput').val();
		$("#ULtree").jstree(true).search(value);
		let searchResult = $('.jstree-search').length;
		if (searchResult < 1) { return };
		$('.jstree-search').each(function (index, obj) {
			if (index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#UL_vision_tree'),
					scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop() - 130);
				container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#UL_vision_tree').height() * 0.3 });
			}
		})
	}
	//公司树删除
	ULdelText() {
		this.mulUpload.selectedCompanyName = '';
		this.mulUpload.selectedCompanyId = '';
		$('#ULcompany').val("");
		$('#ULcompany').val('').change();
		this.ULcompanySearch();
		if ($('#UL_tree_box')[0].className.indexOf('tree_open') > 0) {
			$('#ULcompany').focus();
		}
	}
	//版本升级信息查看(最近五条升级信息)
	versionUpdataDetail(row, modal) {
		modal.show();
		let reqdata = 'deviceId=' + row.deviceId;
		this.jsonApiService.http("log/getRecentUpgrade.html", reqdata).subscribe(data => {
			this.versionUpdataRecord = data.data;
		})
	}
	//跳转系数设置队列
	jumpFactorQueue() {
		//		this.router.navigate(['/algorithm/factor-queue'],{ queryParams: {type:'new'}});
		this.router.navigate(['/algorithm/factor-queue']);
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 300)
	}
	//系数设置日志信息查看(最近五条升级信息)
	coefUpdataDetail(row, modal) {
		modal.show();
		let reqdata = 'deviceId=' + row.deviceId;
		this.jsonApiService.http("deviceCoefLog/findCoefLogByDeviceId.html", reqdata).subscribe(data => {
			for (let item of data.data) {
				if (item.newCoef) {
					let newCoef = [];
					for (let i = 0; i < item.newCoef.length; i++) {
						let _item = item.newCoef[i];
						if (_item) {
							let obj: any = {
								value: item.newCoef[i],
								index: i + 1
							}
							newCoef.push(obj);
						}
					}
					item.newCoef = newCoef;
				} else {
					item.newCoef = [];
				}

				if (item.oldCoef) {
					let oldCoef = [];
					for (let i = 0; i < item.oldCoef.length; i++) {
						let _item = item.oldCoef[i];
						if (_item) {
							let obj: any = {
								value: item.oldCoef[i],
								index: i + 1
							}
							oldCoef.push(obj);
						}
					}
					item.oldCoef = oldCoef;
				} else {
					item.oldCoef = [];
				}

			}
			this.coefUpdataRecord = data.data;
		})
	}
	/**
	 * 设备详细    导航tab切换
	 */
	tableDataTab1: any = [];
	tableDataTab2: any = [];
	tableDataTab2_1: any = [];
	tableDataTab3: any = [];
	tableDataTab4_1: any = [];
	tableDataTab4_2: any = [];
	tableDataTab5: any = [];
	tableDataTab6: any = [];
	totalCountTab: number = 0;
	pageSizeTab: number = 10;
	curPageTab: number = 1; //分页当前页
	activeTab: string = '';
	btnGroupActive: string = '5';//快捷时间按钮(默认三个月);
	btnGroupActiveText: string = '近三个月';//快捷时间按钮文字
	startDateBtn: string = '';
	endDateBtn: string = '';
	/**
	 * 时间快捷选择方式:一周/半个月/一个月/两个月/三个月
	 */
	selectTimeFast(val) {
		this.btnGroupActive = val;
		let temDate = new Date();
		switch (val) {
			case '1':
				this.btnGroupActiveText = '近一周';
				temDate.setDate(temDate.getDate() - 7);//近一周
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			//			case '2':
			//				this.btnGroupActiveText = '近半个月';
			//				temDate.setDate(temDate.getDate() - 15);//近半个月
			//				this.startDateBtn = common.getTimeMmss(temDate);
			//				this.endDateBtn = common.getNowTime();
			//				break;
			case '3':
				this.btnGroupActiveText = '近一个月';
				temDate.setMonth(temDate.getMonth() - 1);//近一个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			//			case '4':
			//				this.btnGroupActiveText = '近两个月';
			//				temDate.setDate(temDate.getDate() - 60);//近两个月
			//				this.startDateBtn = common.getTimeMmss(temDate);
			//				this.endDateBtn = common.getNowTime();
			//				break;
			case '5':
				this.btnGroupActiveText = '近三个月';
				temDate.setMonth(temDate.getMonth() - 3);//近三个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			case '6':
				this.btnGroupActiveText = '近半年';
				temDate.setMonth(temDate.getMonth() - 6);//近半年
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			case '7':
				this.btnGroupActiveText = '全部';
				// temDate.setFullYear(temDate.getFullYear() - 1);//近一年
				this.startDateBtn = '2017-01-01 00:00:00';
				this.endDateBtn = common.getNowTime();
				break;
			default:
				this.btnGroupActive = '5';
				this.btnGroupActiveText = '近三个月';
				temDate.setDate(temDate.getDate() - 90);//默认近三个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
		}
		this.getDeviceInfoData();
		this.getTableDataTab(this.activeTab);
	}
	getTabData(type) {
		this.tableDataTab1 = [];
		this.tableDataTab2 = [];
		this.tableDataTab2_1 = [];
		this.tableDataTab3 = [];
		this.tableDataTab3 = [];
		this.tableDataTab4_1 = [];
		this.tableDataTab4_2 = [];
		this.tableDataTab5 = [];
		this.tableDataTab6 = [];
		this.totalCountTab = 0;
		this.pageSizeTab = 10;
		this.curPageTab = 1;
		this.activeTab = type;
		if (this.btnGroupActive == '5') {
			let temDate = new Date();
			temDate.setDate(temDate.getDate() - 90);//默认近三个月
			this.startDateBtn = common.getTimeMmss(temDate);
			this.endDateBtn = common.getNowTime();
		}
		this.getTableDataTab(type);
	}
	//获取数据:故障信息/维修信息/警报信息/数据修复/固件升级/系数设置
	versionUpdataCount: number;
	coefUpdataCount: number;
	fix: any = {
		totalCount: 0,
		mainCount: 0,
		sensorCount: 0,
		lineCount: 0,
		gpsCount: 0,
		mainQuestion: 0,
		sensorQuestion: 0,
		lineQuestion: 0,
		gpsQuestion: 0,
		firstFixQuestion: '',
		firstFixQuestionTime: '',
		firstSensorQuestion: '',
		firstSensorQuestionTime: '',
		lastSensorQuestion: '',
		lastSensorQuestionTime: '',
		lastGPSQuestion: '',
		lastGPSQuestionTime: '',
	}
	timelineDate: any = [];
	getTableDataTab(type) {
		let reqData: any, param: any;
		switch (type) {
			case '':
				this.getDeviceInfoData();
				break;
			case '1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						carNumber: this.selectRowData.carNumber,
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('dataExceptionRecord/dataRecordPage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
						item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
						item.exceptionType = this.getExceptionTypeName(item.exceptionType);
						item.programType = this.getProgramTypeName(item.programType);
						if (item.coefficient) {
							let coefArr = [];
							for (let i = 0; i < item.coefficient.length; i++) {
								let _item = item.coefficient[i];
								if (_item && _item != '0') {
									var obj = {
										value: item.coefficient[i],
										index: i + 1
									}
									coefArr.push(obj);
								}
							}
							item.coef = coefArr;
						} else {
							item.coef = [];
						}
					}
					this.tableDataTab1 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '2':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						searchKey: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('fixdatalog/logforpage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab2 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '2_1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						searchKey: this.selectRowData.deviceId,
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
						status: "0",
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('exceptionOrderForHaiLuo/findExceptionOrderList.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab2_1 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '3':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('alertlog/deviceShutDownAlarm.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						item.totalSecond = common.secondToDate(item.totalSecond);
					}
					this.tableDataTab3 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '4_1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						repairedStatus: '0',
						dateType: '1',
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceRepaired/findDeviceRepairedList.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					if (result.exhibitDatas.length > 0) {
						for (var i = 0; i < result.exhibitDatas.length; i++) {
							result.exhibitDatas[i].restrictTimeFlag = false
							if (result.exhibitDatas[i].restrictTime) {
								if (
									common.mmsstoTimestamp(common.getNowTime()) -
									common.mmsstoTimestamp(result.exhibitDatas[i].restrictTime) <
									0
								) {
									result.exhibitDatas[i].restrictTimeFlag = true
								}
							}
						}
					}
					this.tableDataTab4_1 = result.exhibitDatas || [];
					this.tableDataTab4_1.map(item => item.callDuration = common.secondToDate(item.callDuration));
					this.totalCountTab = result.recordCount;
				})
				break;
			case '4_2':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						sortType: '2',
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceRepairedV2/findDeviceRepairedV2List.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab4_2 = result.exhibitDatas || [];
					for (let item of this.tableDataTab4_2) {
						var faultPhenomenonList = item.faultPhenomenonList && Array.from(new Set(item.faultPhenomenonList));
						item.faultPhenomenonList = faultPhenomenonList.length > 0 ? faultPhenomenonList.join(",") : '';

						var repairContentList = item.repairContentList && Array.from(new Set(item.repairContentList));
						item.repairContentList = repairContentList.length > 0 ? repairContentList.join(",") : '';

						var repairSubdivideList = item.repairSubdivideList && Array.from(new Set(item.repairSubdivideList));
						item.repairSubdivideList = repairSubdivideList.length > 0 ? repairSubdivideList.join(",") : '';

						item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
					}
					this.totalCountTab = result.recordCount;
					this.repairedDeviceInfo.fixedCount = result.recordCount;
				})
				break;
			case '5':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('log/upgrade.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab5 = result.exhibitDatas || [];
					this.totalCountTab = result.recordCount;
				})
				break;
			case '6':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.selectRowData.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceCoefLog/deviceCoefLogforpage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						if (item.newCoef) {
							let newCoef = [];
							for (let i = 0; i < item.newCoef.length; i++) {
								let _item = item.newCoef[i];
								if (_item) {
									let obj: any = {
										value: item.newCoef[i],
										index: i + 1
									}
									newCoef.push(obj);
								}
							}
							item.newCoef = newCoef;
						} else {
							item.newCoef = [];
						}

						if (item.oldCoef) {
							let oldCoef = [];
							for (let i = 0; i < item.oldCoef.length; i++) {
								let _item = item.oldCoef[i];
								if (_item) {
									let obj: any = {
										value: item.oldCoef[i],
										index: i + 1
									}
									oldCoef.push(obj);
								}
							}
							item.oldCoef = oldCoef;
						} else {
							item.oldCoef = [];
						}

					}
					this.tableDataTab6 = result.exhibitDatas || [];
					this.totalCountTab = result.recordCount;
				})
				break;
			case '8':
				this.addHostAndSensor() //主机和传感器
				// reqData = 'deviceId=' + this.deviceId;
				// this.jsonApiService.http("eventMonitor/eventDataList.html", reqData).subscribe(data => {
				// 	if (data.success && data.data) {
				// 		this.coefUpdataCount = 0;
				// 		this.versionUpdataCount = 0;
				// 		this.fix = {
				// 			totalCount: 0,
				// 			mainCount: 0,
				// 			sensorCount: 0,
				// 			lineCount: 0,
				// 			gpsCount: 0,
				// 			mainQuestion: 0,
				// 			sensorQuestion: 0,
				// 			lineQuestion: 0,
				// 			gpsQuestion: 0,
				// 			firstFixQuestion: '',
				// 			firstFixQuestionTime: '',
				// 			firstSensorQuestion: '',
				// 			firstSensorQuestionTime: '',
				// 			lastSensorQuestion: '',
				// 			lastSensorQuestionTime: '',
				// 			lastGPSQuestion: '',
				// 			lastGPSQuestionTime: '',
				// 		}
				// 		let result = data.data;
				// 		let sensorObj = {}
				// 		for (let item of result) {
				// 			item.eventType1 == 4 ? this.coefUpdataCount += 1 : this.coefUpdataCount = this.coefUpdataCount;
				// 			item.eventType1 == 3 ? this.versionUpdataCount += 1 : this.versionUpdataCount = this.versionUpdataCount;
				// 			item.eventType2 != 0 ? this.fix.totalCount += 1 : this.fix.totalCount = this.fix.totalCount;
				// 			item.eventType2Name == '更换主机' ? this.fix.mainCount += 1 : this.fix.mainCount = this.fix.mainCount;
				// 			item.eventType2Name == '更换传感器' ? this.fix.sensorCount += 1 : this.fix.sensorCount = this.fix.sensorCount;
				// 			item.eventType2Name == '更换线材' ? this.fix.lineCount += 1 : this.fix.lineCount = this.fix.lineCount;
				// 			item.eventType2Name == '更换GPS' ? this.fix.gpsCount += 1 : this.fix.gpsCount = this.fix.gpsCount;
				// 			if (item.eventType2 != 0) {
				// 				item.eventType2 == 202 ? this.fix.firstFixQuestion = null : this.fix.firstFixQuestion = item.eventContent;
				// 				this.fix.firstFixQuestionTime = item.eventTime;
				// 			}
				// 			if (item.eventType2 == 202) {
				// 				this.fix.firstSensorQuestion = item.eventContent;
				// 				this.fix.firstSensorQuestionTime = item.eventTime;
				// 				// 增加传感器问题列表
				// 				let arr = item.eventContent.split("-")
				// 				if (arr.length > 1) {
				// 					// 切分出管道号
				// 					let channel = arr[arr.length - 1]
				// 					item.text1 = "第一次维修CH" + channel
				// 					item.text2 = "第一次维修CH" + channel + "时间"
				// 					if (sensorObj[channel]) {
				// 						// 同一管道只保留最新的数据
				// 						let oldTime = sensorObj[channel].eventTime.replace(/-/g, "/");
				// 						let newTime = item.eventTime.replace(/-/g, "/");
				// 						if (new Date(oldTime).valueOf() > new Date(newTime).valueOf()) {
				// 							sensorObj[channel] = item
				// 						}
				// 					} else {
				// 						sensorObj[channel] = item
				// 					}
				// 				}

				// 			}
				// 			if (item.eventType2 == 202 && !this.fix.lastSensorQuestion) {
				// 				this.fix.lastSensorQuestion = item.eventContent;
				// 				this.fix.lastSensorQuestionTime = item.eventTime;
				// 			}
				// 			if (item.eventType2 == 204 && !this.fix.lastGPSQuestion) {
				// 				this.fix.lastGPSQuestion = item.eventContent;
				// 				this.fix.lastGPSQuestionTime = item.eventTime;
				// 			}
				// 		}
				// 		// 传感器对象进行排序并变成数组的格式
				// 		let sensorArr = (Object.keys(sensorObj)).reduce(function (arr: any, k) {
				// 			arr.push(sensorObj[k])
				// 			return arr
				// 		}, [])
				// 		// 给页面的变量赋值
				// 		this.sensorList = sensorArr.sort(function (a, b) {
				// 			let oldTime = a.eventTime.replace(/-/g, "/");
				// 			let newTime = b.eventTime.replace(/-/g, "/");
				// 			if (new Date(oldTime).valueOf() < new Date(newTime).valueOf()) {
				// 				return -1
				// 			}
				// 		})

				// 		var year = new Date().getFullYear();
				// 		let obj: any;
				// 		this.timelineDate = [];
				// 		for (let i = 2015; i < year + 1; i++) {
				// 			let chrildArr: any = [];
				// 			obj = null;
				// 			for (let item of result) {
				// 				if (item.eventYear == i) {
				// 					chrildArr.push(item);
				// 					obj = {
				// 						date: item.eventYear + '',
				// 						chrild: chrildArr,
				// 						isShow: true,
				// 					}
				// 				}
				// 			}
				// 			if (obj) {
				// 				this.timelineDate.push(obj)
				// 			}
				// 		}
				// 		this.timelineDate = this.timelineDate.reverse();
				if (this.deviceBaseInfo.inputDate) {
					this.deviceBaseInfo.installTime = common.secondToDate((common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceBaseInfo.inputDate)) / 1000)
				}
				// 获取其他的数据接口
				this.jsonApiService.http_obj("system/getRealTimeData.html", { deviceId: this.deviceId }).subscribe(data => {
					this.otherData = data.data
				})
				// 	} else {
				// 		this.timelineDate = [];
				// 		// 提示语句
				// 		layer.msg("该设备未装车", {
				// 			icon: 0
				// 		})
				// 	}
				// })
				break;
			default:
				this.getDeviceInfoData();
				break;

		}
	}
	/**
   * 设备事件 新增主机生命周期和传感器生命周期
   */
	hostTableData: any = [] //主机table列表
	sensorListData: any = [] //传感器table列表
	sensorCount: string = '' //传感器数量
	addHostAndSensor() {
		this.jsonApiService.http_get('matterReplaceInfo/queryMatterReplaceInfoListByDeviceId.html?deviceId=' + this.deviceId).subscribe(data => {
			if (data.success && data.data) {
				let result = data.data
				this.hostTableData = result.hostList || []
				this.sensorListData = result.sensorList ? this.mergeData(result.sensorList, "materielNumber") : []
				this.sensorCount = result.sensorCount
			}
		})
	}
	mergeData(data, indexName) {
		if (data == undefined || data.length == 0 || data == null) {
			return;
		}
		let res = [] //结果数组
		let rowSpan = 1
		for (let i = 0; i < data.length; i++) {
			for (let j = i + 1; j < data.length; j++) {
				if (data[i][indexName] == data[j][indexName]) {
					rowSpan++;
				} else {
					break;
				}
			}
			//开始复制某组相同的数据
			if (rowSpan > 1) {
				for (let k = 0; k < rowSpan; k++) {
					data[k + i].secondIndex = k;
					data[k + i].rowSpan = rowSpan;
					res.push(data[k + i])
				}
				i += (rowSpan - 1) //跳过相同的数据
				rowSpan = 1;
			} else {
				//复制单独的数据
				data[i].secondIndex = 0;
				data[i].rowSpan = rowSpan;
				res.push(data[i])
			}
		}
		return res
	}
	refreshTab() {
		this.getTabData(this.activeTab);
	}
	//分页回调
	paginateTab(e) {
		this.curPageTab = e.page + 1;
		this.pageSizeTab = e.rows;
		this.getTableDataTab(this.activeTab);
	}
	//问题分类
	getExceptionTypeName(key) {
		if (key) {
			return this.questionNameList[key];
		} else {
			return '';
		}
	}
	//现象分类
	getProgramTypeName(key) {
		if (key) {
			return this.questionDeatailNameList[key];
		} else {
			return '';
		}
	}
	questionNameList: any = {
		'1': '算法问题',
		'2': '硬件问题',
		'3': '司机问题',
		'4': '对接问题',
		'5': '运维问题',
		'6': '安装问题'
	};
	questionDeatailNameList: any = {
		'100': '其他',
		'101': '上货问题',
		'102': '卸货问题',
		'103': '在途问题',
		'104': '多次上货',
		'105': '多次卸货',
		'200': '其他',
		'201': '主机问题',
		'202': '传感器问题',
		'203': 'GPS问题',
		'204': '线材问题',
		'300': '其他',
		'301': '司机问题',
		'400': '其他',
		'401': '对接问题',
		'500': '其他',
		'501': '运维问题',
		'601': '安装问题',
		'600': '其他'
	}
	/**
	 * 设备详细(设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	selectRowData: any = {};//选中数据查看的数据row
	deviceDetail(row, modal) {
		if (row == 'btn') {
			this.checkSelectedRow('请选择一条数据进行查看');
			if (!this.selectedRow) {
				return;
			} else {
				this.selectRowData = this.selected[0];
			}
		} else {
			this.selectRowData = row;
		}
		modal.show();
		// $('#deviceDetailModal').modal('show');
		$('.s-lis').removeClass('active');
		$('.tab-pane').removeClass('active');
		$('.s-lis').eq(0).addClass('active');
		$('.s-lis').eq(0).find('a').attr('aria-expanded', 'true');
		$('#all').eq(0).addClass('active');
		this.btnGroupActive = '5'
		let temDate = new Date();
		temDate.setDate(temDate.getDate() - 90);//默认近三个月
		this.startDateBtn = common.getTimeMmss(temDate);
		this.endDateBtn = common.getNowTime();
		this.getDeviceInfoData();
	}
	/**
	 * 关闭设备详情弹窗
	 */
	cancelDeviceDetail(modal) {
		// $('#deviceDetailModal').modal('hide');
		modal.hide();
		this.load();
	}
	/**
	 * 获取设备信息 (设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	deviceBaseInfo: any = {
		companyName: '',
		carNumber: '',
		deviceId: '',
		hwVersion: '',
		useTypeL1: '',
		useTypeL2: '',
		userTypeName: '',
		sensorType: '',
		productNo: '',
		iccid: '',
		driverName: '',
		phone: '',
		inputDate: '',
		userNameForCreate: '',
		sensorChannel: [],
		coef: [],
		coefT: [],
		version: ''
	};
	questionRecordInfo: any = [];//问题记录
	questionRecordTotal: number = 0;//问题记录总和
	dataFixInfo: any = {};//数据修复
	alertDataInfo: any = {};//警报数据
	repairedDeviceInfo: any = {};//维修记录
	deviceRealTimeDataInfo: any = {};//设备实时数据
	isShowGPSAlert: boolean = false;//是否显示GPS数据更新异常警报提示
	isShowOfflineAlert: boolean = false;//是否显示离线警报提示
	offlineDiffTime: string = '';//离线时长
	weightCount: number = 0;//过磅次数
	initDeviceBaseInfo() {
		this.deviceBaseInfo = {
			companyName: '',
			carNumber: '',
			deviceId: '',
			hwVersion: '',
			useTypeL1: '',
			useTypeL2: '',
			userTypeName: '',
			sensorType: '',
			productNo: '',
			iccid: '',
			driverName: '',
			phone: '',
			inputDate: '',
			userNameForCreate: '',
			sensorChannel: [],
			coef: [],
			coefT: [],
			version: ''
		};
		this.isShowGPSAlert = false;
		this.isShowOfflineAlert = false;
		this.questionRecordInfo = [];
		this.dataFixInfo = {};
		this.alertDataInfo = {};
		this.repairedDeviceInfo = {};
		this.deviceRealTimeDataInfo = {};
		this.offlineDiffTime = '';
		this.weightCount = 0;
	}
	getDeviceInfoData() {
		this.initDeviceBaseInfo();
		//设备基本信息
		this.jsonApiService.http_obj("system/getDeviceBaseInfoByDeviceId.html", { deviceId: this.selectRowData.deviceId }).subscribe(data => {
			if (data.success && data.data) {
				for (let item in this.deviceBaseInfo) {
					if (item === 'coef' || item === 'coefT' || item === 'sensorChannel') {
						this.deviceBaseInfo[item] = data.data[item] || [];
					} else {
						this.deviceBaseInfo[item] = data.data[item] || '';
					}
				}
				this.deviceBaseInfo.userTypeName = this.getUseTypeNameL2(this.deviceBaseInfo.useTypeL2);
				if (this.deviceBaseInfo.coef) {
					let coefArr = [];
					for (let i = 0; i < this.deviceBaseInfo.coef.length; i++) {
						let _item = this.deviceBaseInfo.coef[i];
						if (_item) {
							let obj: any = {
								value: _item,
								index: i + 1
							}
							coefArr.push(obj);
						}
					}
					this.deviceBaseInfo.coefT = coefArr;
				} else {
					this.deviceBaseInfo.coefT = [];
				}
			}

		})
		//问题统计(近三个月)
		this.jsonApiService.http_obj("system/countDeviceDataRecordByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.questionRecordTotal = 0;
				this.questionRecordInfo = data.data;
				for (let item of this.questionRecordInfo) {
					this.questionRecordTotal += +item.reasonCount;
				}
			}
		})
		//数据修复统计(近三个月)
		this.jsonApiService.http_obj("system/queryDataFixCountByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.dataFixInfo = data.data;
			}
		})
		//警报统计(近三个月)
		this.jsonApiService.http_obj("system/queryAlarmCountByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.alertDataInfo = data.data;
			}
		})
		//维修记录统计(近三个月)
		this.jsonApiService.http_obj("system/queryDeviceRepairedByDeviceId.html", { deviceId: this.selectRowData.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.repairedDeviceInfo = data.data;
			}
		})
		//设备状态(实时数据)
		let deviceId = this.selectRowData.deviceId;
		this.jsonApiService.http_obj("system/getRealTimeData.html", { deviceId: this.selectRowData.deviceId }).subscribe(data => {
			if (data.success && data.data) {
				this.deviceRealTimeDataInfo = data.data;
				if (JSON.stringify(this.deviceRealTimeDataInfo.markCombination) == '{}') {
					this.deviceRealTimeDataInfo.isEnterFactory = true
				} else {
					if (this.deviceRealTimeDataInfo.markCombination.fakeOnline == 1) {
						this.deviceRealTimeDataInfo.isEnterFactory = false
					} else {
						this.deviceRealTimeDataInfo.isEnterFactory = true
					}

				}
				let carUploadDate, gpsUploadDate;
				if (this.deviceRealTimeDataInfo.carUploadDate) {
					carUploadDate = this.deviceRealTimeDataInfo.carUploadDate;
				}
				if (this.deviceRealTimeDataInfo.gpsUploadDate) {
					gpsUploadDate = this.deviceRealTimeDataInfo.gpsUploadDate;
				}
				if (gpsUploadDate && carUploadDate) {
					let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate));
					abs >= 30 * 60 * 1000 ? this.isShowGPSAlert = true : this.isShowGPSAlert = false; //计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
					this.getWeighbridge(deviceId);
				}
			}
		})
	}
	//获取磅单数据:用于判断离线异常
	getWeighbridge(deviceId) {
		this.jsonApiService.http_obj("weighbridge/weightforreal.html", { deviceId: deviceId, startTime: this.deviceRealTimeDataInfo.updateTime, endTime: common.getNowTime() }).subscribe(data => {
			if (data.success && data.data) {
				this.weightCount = 0;
				let diffTiem = common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceRealTimeDataInfo.updateTime);
				this.offlineDiffTime = common.secondToDate(diffTiem / 1000);//计算离线时长:当前时间 - 最后更新时间
				let weightData = data.data;
				for (let item of weightData) {
					if (+item.weight > 0) {
						this.isShowOfflineAlert = true;
						this.weightCount += 1;//计算榜单数
					}
				}
			}
		})
	}
	/**
	 * 问题记录跳转
	 */
	jumpQuestionByHand(type1, type2, value, modal) {
		if (value == 0) { this.jsonApiService.message('无记录!'); return };
		// $('#deviceDetailModal').modal('hide');
		modal.hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			exceptionType: type1,
			programType: type2
		}
		this.router.navigate(['/abnormal-alert/artificialMonitor']);
		common.setCookie('jumpQuestionByHandList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	/**
	 * 设备警报跳转
	 */
	jumpAlertDataList(type, value, modal) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		// $('#deviceDetailModal').modal('hide');
		modal.hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			type: type,
		}
		this.router.navigate(['/abnormal-alert/device-off']);
		common.setCookie('jumpAlertDataList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	/**
	 * 设备维修跳转
	 */
	jumpRepairedDeviceList(type, dateType, value, modal) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		// $('#deviceDetailModal').modal('hide');
		modal.hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			repairedStatus: type,
			dateType: dateType,
		}
		if (type == '0') {
			this.router.navigate(['/device-management/fault']);
		} else if (type == '1') {
			this.router.navigate(['/device-management/faultV2']);
		}
		common.setCookie('jumpRepairedDeviceList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	jumpDataFixList(type, value, modal) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		// $('#deviceDetailModal').modal('hide');
		modal.hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			type: null
		}
		switch (type) {
			case '1':
				queryParams.type = '1';
				this.router.navigate(['/log-info/repairRecord']);
				common.setCookie('jumpDataFixList', JSON.stringify(queryParams));
				break;
			case '2':
				queryParams.type = '2';
				this.router.navigate(['/log-info/repairRecord']);
				common.setCookie('jumpDataFixList', JSON.stringify(queryParams));
				break;
			case '3':
				queryParams.type = '0';
				this.router.navigate(['/abnormal-alert/order']);
				common.setCookie('jumpExceptionOrderList', JSON.stringify(queryParams));
				break;
			default:
				break;
		}
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)

	}
	modal: any = { //图片弹窗
		picture: '',
		carNumber: ''
	};
	//查看照片
	// open_img(row,val){
	// 	val.show();
	// 	this.modal.carNumber = row.carNumber;
	// 	if(row.deviceImageUrl){
	// 		this.modal.picture = config.BaseURL+row.deviceImageUrl.substring(1,row.deviceImageUrl.length);
	// 	}
	// }
	//关闭图片弹窗
	// imgClose(val){
	// 	this.modal.carNumber = '';
	// 	this.modal.picture = '';
	// 	val.hide();
	// }
	// 点击按钮
	changeRelease(type, modal, openModal) {
		let msg = ""
		if (type == "releaseToNo") {
			msg = '是否将车辆解除放行';
			this.jsonApiService.confirm_message(msg).then(() => {
				let reqdata = 'deviceId=' + this.selectRowData.deviceId + '&enterFactoryMark=0';
				this.jsonApiService.http("realtime/setEnterFactoryMark.html", reqdata).subscribe(data => {
					this.jsonApiService.message(data.message);
					if (data.success) {
						// 刷新详情框
						this.deviceDetail(this.selectRowData, modal)
					}
				})
			})
		} else if (type == "noToRelease") {
			msg = '是否要将车辆放行';
			this.isPushTime = 0.5; // 默认的放行时间
			openModal.show();
		}
	}
	lgisPush: any = 'time'; // 默认选中单选框
	isPushTime: any = 0.5; // 默认的放行时间
	replaceFactoryGps: any = 0;// 是否替换0：不替换，1：替换
	releaseCompanyId: any = '';// 替换的厂区ID
	// 进厂放行弹框关闭
	lgModalhide(modal) {
		modal.hide();
	}
	//自定义限制,校验非空值,默认6小时,不允许为空
	inputChange() {
		this.isPushTime = Math.abs(this.isPushTime);
		if (!this.isPushTime) {
			this.isPushTime = 0.5;
		}
	}
	//是否替换厂区change事件
	radioChange(checked, type) {
		if (type === '0' && checked) {
			this.replaceFactoryGps = 0;
		} else if (type === '1' && checked) {
			this.replaceFactoryGps = 1;
		}
	}
	// 放行厂区选择
	releaseCompanySelected(data) {
		this.releaseCompanyId = data.companyId;
		// this.selectedCompanyName = data.companyName;
	}
	// 进厂放行的配置
	setTimeSubmit(modal, detailModal) {
		let time = this.isPushTime * 3600
		if (!Number(time)) {
			this.jsonApiService.message("请输入正确的时间格式");
			return
		}
		let reqdata = 'deviceId=' + this.selectRowData.deviceId + '&enterFactoryMark=1&time=' + time + '&replaceFactoryGps=' + this.replaceFactoryGps + '&companyId=' + this.releaseCompanyId;
		this.jsonApiService.http("realtime/setEnterFactoryMark.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				// 刷新详情框
				modal.hide();
				this.deviceDetail(this.selectRowData, detailModal)
			}
		})
	}
	/**
	 * 设置厂区在线
	 */
	// 点击弹出设置厂区在线的弹框
	setFactoryOnline(modal) {
		// 清空公司树
		this.factoryOnlineCompanyComp.resetData();
		this.factoryOnlineSearchKey = ""
		//这里还要做加载表单
		this.loadFactoryOnline()
		modal.show();
	}
	@ViewChild('factoryOnlineComponent')
	factoryOnlineCompanyComp: CompanyTreeCarComponent
	// 关闭厂区在线弹框
	cancelFactoryOnline(modal) {

		modal.hide();
	}
	// 表单刷新
	factoryTableRefresh() {
		this.loadFactoryOnline();
	}
	//分页回调
	factoryPaginate(e) {
		this.factoryOnlineCurPage = e.page + 1;
		this.factoryOnlinePageSize = e.rows;
		this.loadFactoryOnline();
	}
	// 设置厂区在线的公司选择回调
	onlinecompanySelected(data) {
		// 请求验证接口
		this.onlineSetCompanyId = data.companyId;
	}
	// 搜索
	factoryOnlineSearch() {
		this.factoryOnlineCurPage = 1
		this.loadFactoryOnline();
	}
	// 加载厂区表数据
	loadFactoryOnline() {
		let param = {
			"pageSize": this.factoryOnlinePageSize,
			"nowPage": this.factoryOnlineCurPage,
			"parameters": {
				companyId: this.onlineSetCompanyId, 			// 公司id
				searchKey: this.factoryOnlineSearchKey,				// 版本号
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("factory/list.html", reqdata).subscribe(data => {
			this.factoryOnlineTableData = data.exhibitDatas;
			this.factoryOnlinetotalCount = data.recordCount;
		})
	}
	// 关键字搜索
	factory_table_search() {
		this.factoryOnlineCurPage = 1;
		this.factoryOnlineSearchKey = common.stringTrim(this.factoryOnlineSearchKey);
		this.loadFactoryOnline();
	}

	// 添加厂区的实体对象
	factory: any = {
		companyId: "",     	//公司id
		companyName: "",		//公司名称
		r: "",				//半径
		lng: "",				//经度
		lat: "",				//纬度
		remark: ""			//描述
	}
	// 添加厂区弹窗
	factoryAdd(modal) {
		this.factory = {
			companyId: "",     	//公司id
			companyName: "",		//公司名称
			r: "",				//半径
			lng: "",				//经度
			lat: "",				//纬度
			remark: ""			//描述
		}
		this.selectedCompanyName3 = "";
		this.selectedCompanyId3 = "";
		$('#colse').trigger("click");// 关闭地图
		modal.show();
	}
	// 编辑厂区弹窗
	editFactory(row, modal) {
		$("#suggestId").val("") // 清空地图搜索框
		this.factory = JSON.parse(JSON.stringify(row));
		this.selectedCompanyName3 = row.companyName;
		this.selectedCompanyId3 = row.companyId;
		modal.show();
		// 显示地图 并且重新定位
		$('#allMap').show();
		let timer = setTimeout(() => {
			$('#positionBtn').trigger("click"); //点击编辑重新定位位置
			clearTimeout(timer)
			timer = null
		}, 300);
	}
	// 公司选中回调
	factorySelected(data) {
		this.selectedCompanyId3 = data.companyId;
		this.selectedCompanyName3 = data.companyName;
		if (data.companyId) {
			this.searchCompanyName(data.companyId);
		} else {
			this.factory.lng = '';
			this.factory.lat = '';
			this.factory.r = '';
		}

	}
	//携带出车辆得经纬度
	searchCompanyName(id) {
		this.jsonApiService.http("company/companyInfo.html", 'id=' + id).subscribe(data => {
			this.factory.lng = data.data.lng;
			this.factory.lat = data.data.lat;
			this.factory.r = 1000;
		})
	}
	// 关闭弹框
	closeFactory(modal) {
		$("#setFactoryFrom").data('bootstrapValidator').resetForm();
		modal.hide();
	}
	// 删除厂区
	delFactory(row) {
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除').then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("factory/delete.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.loadFactoryOnline();
				}
			})
		})
	}

	// 添加提交
	addSubmitFactory(modal) {
		this.factory.companyId = this.selectedCompanyId3
		this.factory.companyName = this.selectedCompanyName3
		$('#setFactoryFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#setFactoryFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.jsonApiService.http_obj("factory/add.html", this.factory).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					//
					this.loadFactoryOnline();
					this.closeFactory(modal)
				}
			})
		}
	}
	// 编辑提交
	editSubmitFactory(modal) {
		this.factory.companyId = this.selectedCompanyId3
		this.factory.companyName = this.selectedCompanyName3
		$('#setFactoryFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#setFactoryFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if (isValid) {
			this.jsonApiService.http_obj("factory/update.html", this.factory).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					//
					this.loadFactoryOnline();
					this.closeFactory(modal)
				}
			})
		}
	}
	// 地图初始化
	initMap() {
		let that = this;
		var map = new BMap.Map("allMap", { enableMapClick: false });



		var myCity = new BMap.LocalCity();//获取用户当前所在城市
		myCity.get(function (result) {
			let point = result.center;
			let city = new BMap.Point(point.lng, point.lat); //创建点坐标
			map.centerAndZoom(city, 14); //初始化地图，设置中心点坐标和地图级别
		});


		// map.centerAndZoom(new BMap.Point(116.404, 39.915), 14);
		map.enableScrollWheelZoom();
		let mapSize = 14;
		map.addEventListener("zoomend", function () {
			mapSize = this.getZoom();
		});
		let point;
		//		地图click事件
		map.addEventListener("click", function (e) {
			point = e.point;
			var marker = new BMap.Marker(point);        // 创建标注
			map.clearOverlays();
			map.addOverlay(marker);
			// 点击时候给点击的位置转为GPS的 并且回显输入框
			let factoryPosition = toWGS84(point)
			that.factory.lng = factoryPosition.lng;
			that.factory.lat = factoryPosition.lat;
			$('#longitude').val(factoryPosition.lng).change();
			$('#latitude').val(factoryPosition.lat).change();
		});

		//		单击打开地图定位
		$('#positionBtn').click(function (e) {
			e.preventDefault();
			map.clearOverlays();
			$('#allMap').show(function () {	//回调
				$('#colse').show(0);
				$("#searchWrap").show()
				let lat = $('#latitude').val();
				let lng = $('#longitude').val();
				let radiusLength = $("#radius").val();
				let point = { lat: lat, lng: lng }
				// 将用户输入的gps坐标转换为百度点进行地图打点
				let baiduPoint = toMapPoint(point);
				if (radiusLength) {
					var point1 = new BMap.Point(baiduPoint.lng, baiduPoint.lat);
					var circle = new BMap.Circle(point1, radiusLength, {
						strokeColor: 'blue',
						fillColor: 'red',
						strokeWeight: 1,
						strokeOpacity: 0.2,
						fillOpacity: 0.2
					});
					map.clearOverlays()
					map.addOverlay(circle);
					map.centerAndZoom(point1, mapSize);	//定位中心点
				}
				if (!lat && !lng) {
					var myCity = new BMap.LocalCity();//获取用户当前所在城市
					myCity.get(function (res) {
						if (res.center.lng && res.center.lat) {
							var pointCenter = new BMap.Point(res.center.lng, res.center.lat);
							map.centerAndZoom(pointCenter, mapSize);	//定位中心点
						}
						else {
							myCity.get(function (result) {
								let point = result.center;
								let city = new BMap.Point(point.lng, point.lat); //创建点坐标
								map.centerAndZoom(city, 14); //初始化地图，设置中心点坐标和地图级别
								var markerCenter = new BMap.Marker(pointCenter);
								if (lat && lng) {
									map.addOverlay(markerCenter);
								}
							});
						}
					});
				}
				//输入经纬度则定位到对应位置
				if (lat && lng) {
					var pointCenter = new BMap.Point(baiduPoint.lng, baiduPoint.lat);
					map.centerAndZoom(pointCenter, mapSize);	//定位中心点
					var markerCenter = new BMap.Marker(pointCenter);
					if (lat && lng) {
						map.addOverlay(markerCenter);
					}
				}
				//没有输入经纬度，默认定位到当前定位
				else {
					var myCity = new BMap.LocalCity();//获取用户当前所在城市
					myCity.get(function (result) {
						let point = result.center;
						let city = new BMap.Point(point.lng, point.lat); //创建点坐标
						map.centerAndZoom(city, 14); //初始化地图，设置中心点坐标和地图级别
						var markerCenter = new BMap.Marker(pointCenter);
						if (lat && lng) {
							map.addOverlay(markerCenter);
						}
					});
				}
			});
		});

		//		单击位置预览
		$('#circleBtn').click(function () {
			$('#positionBtn').trigger("click")
			let radius = $('#radius').val();
			let latitude = $('#latitude').val();
			let longitude = $('#longitude').val();
			let point = { lat: latitude, lng: longitude }
			// 将用户输入的gps坐标转换为百度点进行地图打点
			let baiduPoint = toMapPoint(point);
			if (radius && latitude && longitude) {
				var point1 = new BMap.Point(baiduPoint.lng, baiduPoint.lat);
				var circle = new BMap.Circle(point1, radius, {
					strokeColor: 'blue',
					fillColor: 'red',
					strokeWeight: 1,
					strokeOpacity: 0.2,
					fillOpacity: 0.2
				});
				map.clearOverlays();
				map.addOverlay(circle);
				map.centerAndZoom(point1, 12);
			} else {
				layer.msg('请输入经纬度跟半径', {
					icon: 0
				});
			}

		});
		// 关闭地图
		$('#colse').click(function () {
			$(this).hide();
			map.clearOverlays();
			$('#allMap').hide();
			$("#suggestId").val("")
			$("#searchWrap").hide()
			// 清空点击搜索地图存的值
			that.myMap = "";
			that.myValue = ""
		});

		// 地图搜索功能
		// 百度地图API功能
		var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{
				"input": "suggestId"
				, "location": map
			});
		ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
			var str = "";
			var _value = e.fromitem.value;
			var value = "";
			if (e.fromitem.index > -1) {
				value = _value.province + _value.city + _value.district + _value.street + _value.business;
			}
			str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province + _value.city + _value.district + _value.street + _value.business;
			}
			str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			document.getElementById("searchResultPanel").innerHTML = str;
		});
		var myValue;
		ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
			var _value = e.item.value;
			myValue = _value.province + _value.city + _value.district + _value.street + _value.business;

			document.getElementById("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
			that.myMap = map;
			that.myValue = myValue;
			that.setPlace(map, myValue);
		});
	}

	// 标记点
	setPlace(map, myValue) {
		let that = this
		map.clearOverlays();    //清除地图上所有覆盖物
		function myFun() {
			var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
			// 将百度地图搜索出来的位置转换为GPS坐标
			let p = JSON.parse(JSON.stringify(pp))
			let gpsPoint = toWGS84(p);
			that.factory.lng = gpsPoint.lng;
			that.factory.lat = gpsPoint.lat;
			$('#longitude').val(gpsPoint.lng).change();
			$('#latitude').val(gpsPoint.lat).change();
			map.centerAndZoom(pp, 18);
			map.addOverlay(new BMap.Marker(pp));    //添加标注
		}
		var local = new BMap.LocalSearch(map, { //智能搜索
			onSearchComplete: myFun
		});
		local.search(myValue);
	}
	// 点击搜索再次搜索  用两个变量来保存刚才的值
	myMap = "";
	myValue = "";
	clickSearchMap() {
		// 如果有值就渲染
		if (this.myValue) {
			this.setPlace(this.myMap, this.myValue)
		}
	}
	imgInfo: any = []; //单个图片列表
	//查看照片
	open_img(row, val) {
		this.imgInfo = [];
		val.show();
		this.modal.carNumber = row.carNumber;
		for (var b = 0; b < row.imageInfo.length; b++) {
			row.imageInfo[b].localImg = [];
			for (let c = 0; c < row.imageInfo[b].imageList.length; c++) {
				// let localImg;
				// if(row.imageInfo[b].imageList[c][0] == '/'){
				// 	localImg = config.BaseURL + row.imageInfo[b].imageList[c].substr(1);
				// }else{
				// 	localImg = config.BaseURL + row.imageInfo[b].imageList[c];
				// }

				let localImg;
				if (row.imageInfo[b].imageList[c].indexOf('http') == -1) {
					if (row.imageInfo[b].imageList[c][0] == '/') {
						localImg = config.BaseURL + row.imageInfo[b].imageList[c].substr(1);
					} else {
						localImg = config.BaseURL + row.imageInfo[b].imageList[c];
					}
				} else {
					localImg = row.imageInfo[b].imageList[c];
				}
				row.imageInfo[b].localImg.push(localImg);
			}
		}
		this.imgInfo = row.imageInfo
		if (this.isViewer && $(".viewer-container").length > 0) {
			this.viewer.destroy();
		}
	}
	//关闭图片弹窗
	imgClose(val) {
		this.modal.carNumber = '';
		this.modal.picture = '';
		val.hide();
	}
	bigImg: any = ''// 放大的图片
	//图片放大
	bigimg(modal, row) {
		// modal.show();
		this.bigImg = row
		if (this.isViewer && $(".viewer-container").length > 0) {
			System.import('assets/js/viewer/viewer.js').then(
				() => {
					System.import('assets/js/viewer/bootstrap.bundle.min.js').then(
						() => {
							System.import('assets/js/viewer/viewer.css').then(() => {
								this.showImg();
							})
						})
				})
		} else {
			this.showImg();
		}
	}
	//显示图片组件
	viewer: any = '';
	showImg() {
		var that = this;
		var imgList = $(".imagesInfo")[0];
		this.viewer = new Viewer(imgList, {
			url: 'src',
			title: function (image) {
				return image.alt + ' (' + (this.index + 1) + '/' + this.length + ')';
			},
		});
		that.isViewer = true
	}
	CloseBigImg(modal) {
		modal.hide();
	}



	//批量设置
	mulUploadTap: any = '1' //选项卡 批量设置 默认是1：上传频率  2批量读取硬件版本号 3批量读取ICCID

	mulUploadClick(type) {
		this.mulUploadTap = type;
	}

	/**
	 * 离线统计的所有方法
	 */
	@ViewChild('offlineCompanyComponent')
	offlineCompanyComp: CompanyTreeCarComponent
	// 离线统计
	offLineManage(modal) {
		// 清空查询条件
		this.offlineType = "3"
		this.alarmType = ""
		this.hardVersion = ""
		// 重置公司和车辆选择
		this.offlineCompanyComp.resetData()
		this.getOfflineCount();
		//这里还要做加载表单
		this.loadOfflineTable()
		modal.show();

	}
	// 关闭离线统计
	canceloffline(modal) {
		modal.hide();
	}
	//分页回调
	offlinePaginate(e) {
		this.offlineCurPage = e.page + 1;
		this.offlinePageSize = e.rows;
		this.loadOfflineTable();
	}
	// 表单刷新
	offlineTableRefresh() {
		this.loadOfflineTable();
	}
	// 离线的公司和车辆选择
	offlineCompanySelected(data) {
		this.offlineDeviceId = data.deviceId;
		this.offlineCompanyId = data.companyId;
	}
	// 获取离线类型统计的数量
	getOfflineCount() {
		let param = {
			"pageSize": this.offlinePageSize,
			"nowPage": this.offlineCurPage,
			"parameters": {
				deviceId: this.offlineDeviceId, 			// 设备Id
				companyId: this.offlineCompanyId, 		// 公司id
				// type: this.offlineType,				// 离线类型
				alarmType: this.alarmType,       // 警报类型
				searchKey: this.hardVersion.trim(), // 硬件版本
				startTime: this.offline_startTime,
				endTime: this.offline_endTime
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("system/offLineStatisCount.html", reqdata).subscribe(data => {
			console.log(data)
			if (data.success) {
				this.offlineCountArray = data.data
			}
		})
	}
	// 加载
	loadOfflineTable() {
		let param = {
			"pageSize": this.offlinePageSize,
			"nowPage": this.offlineCurPage,
			"parameters": {
				deviceId: this.offlineDeviceId, 			// 设备Id
				companyId: this.offlineCompanyId, 		// 公司id
				type: this.offlineType,				// 离线类型
				alarmType: this.alarmType,       // 警报类型
				searchKey: this.hardVersion.trim(), // 硬件版本
				startTime: this.offline_startTime,
				endTime: this.offline_endTime
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(param);
		this.jsonApiService.http("system/offLineStatis.html", reqdata).subscribe(data => {
			this.offlineTableData = data.exhibitDatas;
			this.offlinetotalCount = data.recordCount;
		})
	}
	// 离线表单查询
	offline_table_search() {
		this.offlineCurPage = 1;
		// this.offlineSearchKey = common.stringTrim(this.searchKey);
		// 点击查询时修改离线数量统计
		this.getOfflineCount();
		this.loadOfflineTable();
	}
	// 切换离线类型
	changeOffilineType(type) {
		this.offlineType = type
		// 切换离线类型时也修改离线数量统计
		this.getOfflineCount();
		this.loadOfflineTable();
	}
	// 接收子组件传递过来的数据
	getSelectTableTime(time) {
		this.offline_startTime = time.startTime;
		this.offline_endTime = time.endTime;
	}

	/**
	 *
	 *
	 * 表头管理
	 *
	 *
	 *
	*/
	faultJson: any = [{
		"field": "勾选",
		"fieldName": "isChecked",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 1
	}, {
		"field": "操作",
		"fieldName": "operation",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 2
	}, {
		"field": "公司名称",
		"fieldName": "companyName",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 3
	}, {
		"field": "车牌号",
		"fieldName": "carNumber",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 4
	}, {
		"field": "设备ID",
		"fieldName": "deviceId",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 5
	}, {
		"field": "重量(吨)",
		"fieldName": "weight",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 6
	}, {
		"field": "车辆分类",
		"fieldName": "useTypeL2",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 7
	}, {
		"field": "重量时间",
		"fieldName": "carUploadDate",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 8
	}, {
		"field": "GPS时间",
		"fieldName": "gpsUploadDate",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 9
	}, {
		"field": "状态",
		"fieldName": "isEnterFactory",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 10
	}, {
		"field": "软件版本",
		"fieldName": "version",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 11
	}, {
		"field": "硬件版本",
		"fieldName": "hwVersion",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 12
	}, {
		"field": "传感器通道",
		"fieldName": "sensorChannelT",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 13
	}, {
		"field": "系数",
		"fieldName": "coef",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 14
	}, {
		"field": "安装时间",
		"fieldName": "installTime",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 15
	}, {
		"field": "备注",
		"fieldName": "remark",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 16
	}, {
		"field": "操作",
		"fieldName": "operation1",
		"mark": "system:runStatus",
		"menuName": "车辆运行状态",
		"isHide": 0,
		"order": 17
	}
	]
	isSwitch: boolean = false; //默认隐藏
	faultList: any = []; //页面jsonList
	faultPopupList: any = []; //弹窗jsonList
	//插入数据库表头
	insertHeader() {
		this.jsonApiService.http_obj("header/insertBatchHeader.html", { headerEntityList: JSON.stringify(this.faultJson) }).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.reaustHeader(); //再次请求表头
			}
		})
	}
	//请求表头
	reaustHeader() {
		this.jsonApiService.http_obj("header/field.html", { mark: 'system:runStatus' }).subscribe(data => {
			if (!data.success) {
				this.insertHeader();
			} else {
				var dataList = data.data.headerList;

				for (let i = 0; i < dataList.length; i++) {
					if (dataList[i].isHide == 0) {
						dataList[i].isStatus = true
					} else {
						dataList[i].isStatus = false
					}
					dataList[i].order = i + 1;
				}
				this.faultList = JSON.parse(JSON.stringify(dataList));
				this.faultPopupList = JSON.parse(JSON.stringify(dataList));
			}
		})
	}
	//初始化开关
	initSwitch() {
		var that = this;
		$('.isStatus').bootstrapSwitch({    //初始化按钮
			onText: "显示",
			offText: "隐藏",
			onColor: "primary",
			offColor: "warning",
			onSwitchChange: function (event, state) {
				console.log(state)
				// state 为true 0隐藏  false 1不隐藏
				if (state == true) {
					that.checkStatus(0, event.target.attributes.key.nodeValue);
				} else {
					that.checkStatus(1, event.target.attributes.key.nodeValue);
				}
			}
		});
	}
	setHeader(modal) {
		var that = this;
		this.faultPopupList = JSON.parse(JSON.stringify(this.faultList));
		modal.show();
		System.import('assets/js/bootstrap-switch.min.js').then(
			() => {
				System.import('assets/css/bootstrap-switch.min.css').then(() => {
					setTimeout(function () {
						that.initSwitch();
						that.isSwitch = true
					}, 1)

				})
			});
	}
	//关闭表头弹窗
	closeHeader(modal) {
		modal.hide();
		this.isSwitch = false;
	}
	//重置表头
	recoveryHeader() {
		var that = this;

		this.faultPopupList = JSON.parse(JSON.stringify(this.faultList));

		System.import('assets/js/bootstrap-switch.min.js').then(
			() => {
				System.import('assets/css/bootstrap-switch.min.css').then(() => {
					setTimeout(function () {
						that.initSwitch();
						that.isSwitch = true
					}, 1)

				})
			});

	}
	//确定提交表头
	submitHeader(modal) {

		var mark = 'system:runStatus';
		var field = [];
		var fieldName = [];
		var isShow = [];
		for (var i = 0; i < this.faultPopupList.length; i++) {
			field.push(this.faultPopupList[i].field);
			fieldName.push(this.faultPopupList[i].fieldName);
			isShow.push(this.faultPopupList[i].isHide);
		}
		var reqdata = new FormData();

		reqdata.append('mark', mark);
		reqdata.append('field', field.join(","));
		reqdata.append('fieldName', fieldName.join(",")); //type 1获取相对路径  2获取绝对路径
		reqdata.append('isShow', isShow.join(","));

		this.jsonApiService.form_http("header/updateBatchHeader.html", reqdata).subscribe(data => {
			if (data.success) {
				modal.hide();
				this.isSwitch = false;
				this.reaustHeader(); //请求表头
				this.load();
			}
		})
	}
	//移动 type 1:上移  2：下移  3：置顶  4：置底
	MoveClick(row, type) {
		var that = this;
		if (row.order == 1) {
			if (type == "1") {
				this.jsonApiService.message("已经在第一位，暂不能上移");
				return;
			} else if (type == "3") {
				this.jsonApiService.message("已经在第一位，暂不能置顶");
				return;
			}

		}

		if (row.order == this.faultPopupList.length) {
			if (type == "2") {
				this.jsonApiService.message("已经在最后一位，暂不能下移");
				return;
			} else if (type == "4") {
				this.jsonApiService.message("已经在最后一位，暂不能置底");
				return;
			}
		}

		var List = JSON.parse(JSON.stringify(this.faultPopupList));
		for (var i = 0; i < List.length; i++) {
			if (List[i].order == row.order) {
				if (type == "1") {
					List[i - 1].order = List[i - 1].order + 1;
					List[i].order = row.order - 1;
					break;
				} else if (type == "2") {
					List[i + 1].order = List[i + 1].order - 1;
					List[i].order = row.order + 1;
					break;
				} else if (type == "3") {
					List[i].order = 1;
				} else if (type == "4") {
					List[i].order = List.length;
				}

			} else {
				if (List[i].order > row.order && type == "4") {
					List[i].order = List[i].order - 1;
				} else if (List[i].order < row.order && type == "3") {
					List[i].order = List[i].order + 1
				}
			}
		}

		List = List.sort(this.compare('order'))
		this.faultPopupList = JSON.parse(JSON.stringify(List));

		System.import('assets/js/bootstrap-switch.min.js').then(
			() => {
				System.import('assets/css/bootstrap-switch.min.css').then(() => {
					setTimeout(function () {
						that.initSwitch();
						that.isSwitch = true
					}, 1)

				})
			});
	}
	compare(property) {
		return function (a, b) {
			var value1 = a[property];
			var value2 = b[property];
			return value1 - value2;
		}
	}

	//是否启用
	checkStatus(check, key) {
		var that = this;
		var List = JSON.parse(JSON.stringify(this.faultPopupList));
		for (var i = 0; i < List.length; i++) {
			if (List[i].fieldName == key) {
				if (check == "0") {
					List[i].isHide = check;
					List[i].isStatus = true;
				} else {
					List[i].isHide = check;
					List[i].isStatus = false;
				}
			}
		}

		List = List.sort(this.compare('order'))
		this.faultPopupList = JSON.parse(JSON.stringify(List));

		System.import('assets/js/bootstrap-switch.min.js').then(
			() => {
				System.import('assets/css/bootstrap-switch.min.css').then(() => {
					setTimeout(function () {
						that.initSwitch();
						that.isSwitch = true
					}, 1)

				})
			});
	}
	// 离线统计的导出
	export_offline() {
		var parameters = {
			deviceId: this.offlineDeviceId, 			// 设备Id
			companyId: this.offlineCompanyId, 		// 公司id
			type: this.offlineType,				// 离线类型
			alarmType: this.alarmType,       // 警报类型
			searchKey: this.hardVersion.trim(), // 硬件版本
			startTime: this.offline_startTime,
			endTime: this.offline_endTime
		};
		let timeCheck = common.correctTime(parameters, ['type'])
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		common.exprotDataFile(parameters, 'param', config.BaseURL + 'system/exportOffLineStatis.html')
	}




	//信噪比检测
	frequency: any = '5'; //检测频率 默认3秒  可修改
	DetectionTimes: any = '10'; //默认10次开始 可修改
	TestingTimes: any = 0; //默认从0开始累加
	answerTimes: any = 0; //应答次数 默认从0开始累加
	isShowStartBtn: any = true; //是否显示开始按钮，true是；false否
	SignalTestingData: any = {
		"code_04D9": "", //GPS定位卫星
		"code_04DA": "", //北斗定位卫星
		"code_04D0": "",//定位状态
		"code_0407": "",//采集时间
		"code_0408": "",//GPS时间
		"code_0409": "",//GPS经度
		"code_040C": "",//GPS速度
		"code_04D8": "",//GPS模块
		"code_040B": "",//GPS航向
		"code_040A": "",//GPS纬度
		"code_041D": "",//信号强度
		"code_04D7": "",//GPS天线
		"code_04DB": "",//GPS可视卫星
		"code_04DC": "",//北斗可视卫星
		"code_deviceId": "",
		"isShowRedTime": false //GPS时间标红
	}
	echart_Xdata: any = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32];
	echart_GPSData: any = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //GPS信噪比
	echart_NorthData: any = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //北斗信噪比
	echart_GPS: any;
	echart_North: any;
	option_GPS: any = {
		backgroundColor: '#EFEFEF',
		xAxis: {
			type: 'category',
			data: this.echart_Xdata,
			// axisLabel:{
			// 	inside: true,
			// 	textStyle: {
			// 		color: '#333'
			// 	}
			// },
			// z: 10
		},
		yAxis: {
			type: 'value'
		},
		series: [{
			data: this.echart_GPSData,
			type: 'bar',
			showBackground: true,
			// backgroundStyle: {
			// 	color: 'rgba(220, 220, 220, 0.8)'
			// },
			barCategoryGap: "1px",
			label: {
				show: true,
				position: "top",
				color: "#333"
			},
			itemStyle: {
				normal: {
					color: function (params) {
						var index_color = params.value;
						if (index_color < 11) {
							return '#ff0000';
						} else if (index_color > 10 && index_color < 21) {
							return '#fbff00';
						} else {
							return '#17c50b';
						}
					}
				}
			},
		}],
		grid: {
			left: 35,
			right: 30,
			top: 30,
			bottom: 25
		},
	}
	option_North: any = {
		backgroundColor: '#EFEFEF',
		xAxis: {
			type: 'category',
			data: this.echart_Xdata,
			// axisLabel:{
			// 	inside: true,
			// 	textStyle: {
			// 		color: '#333'
			// 	}
			// },
			z: 10
		},
		yAxis: {
			type: 'value'
		},
		series: [{
			data: this.echart_NorthData,
			type: 'bar',
			showBackground: true,
			// backgroundStyle: {
			// 	color: 'rgba(220, 220, 220, 0.8)'
			// },
			barCategoryGap: "1px",
			label: {
				show: true,
				position: "top",
				color: "#333"
			},
			itemStyle: {
				normal: {
					color: function (params) {
						var index_color = params.value;
						if (index_color < 11) {
							return '#ff0000';
						} else if (index_color > 10 && index_color < 21) {
							return '#fbff00';
						} else {
							return '#17c50b';
						}
					}
				}
			},
		}],
		grid: {
			left: 35,
			right: 30,
			top: 30,
			bottom: 25
		},
	}
	SignalTesting(modal) {
		var that = this;
		if (!that.protocolVersion) {
			that.jsonApiService.message('请选择需要检测的版本');
			return;
		}
		if (that.selected.length == 0) {
			that.jsonApiService.message('请选择需要检测设备的车辆');
			return;
		}
		if (that.selected.length > 1) {
			that.jsonApiService.message('只能选择一个需要检测的设备');
			return;
		}
		if (that.selected[0].runStatus === '0') {
			that.jsonApiService.message('离线状态下的设备不能进行检测信噪比');
			return;
		}

		that.frequency = '5';
		that.DetectionTimes = '10'
		that.TestingTimes = 0;
		that.answerTimes = 0;
		that.isShowStartBtn = true;
		clearInterval(that.requestTimes);

		that.SignalTestingData = {
			"code_04D9": "", //GPS定位卫星
			"code_04DA": "", //北斗定位卫星
			"code_04D0": "",//定位状态
			"code_0407": "",//采集时间
			"code_0408": "",//GPS时间
			"code_0409": "",//GPS经度
			"code_040C": "",//GPS速度
			"code_04D8": "",//GPS模块
			"code_040B": "",//GPS航向
			"code_040A": "",//GPS纬度
			"code_041D": "",//信号强度
			"code_04D7": "",//GPS天线
			"code_04DB": "",//GPS可视卫星
			"code_04DC": "",//北斗可视卫星
			"code_deviceId": that.selected[0].deviceId,
			"isShowRedTime": false //GPS时间标红
		}


		modal.show();

		//initEchart
		if (!that.echart_GPS) {
			this.echart_GPS = echarts.init(document.getElementById('GPSEchart'));
		}
		if (!that.echart_North) {
			this.echart_North = echarts.init(document.getElementById('northEchart'));
		}
		this.initChart();
		$(window).trigger('resize');

		window.onresize = function () {
			that.echart_GPS.resize();
			that.echart_North.resize();
		}

	}
	//初始化echart图
	initChart() {
		this.echart_GPSData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //GPS信噪比
		this.option_GPS.series[0].data = this.echart_GPSData;
		this.echart_GPS.setOption(this.option_GPS, true);

		this.echart_NorthData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //北斗信噪比
		this.option_North.series[0].data = this.echart_NorthData;
		this.echart_North.setOption(this.option_North, true);

	}
	signalTestingModalhide(modal) {
		modal.hide();
	}
	requestTimes: any; //定时器
	//开始轮询查询接口
	startSubmit() {
		var that = this;
		that.answerTimes = 0;
		var vesion = that.protocolVersion;
		var id = that.selected[0].deviceId;
		this.isShowStartBtn = false;

		//开始请求一次
		that.requestTesting(vesion, id);
		that.TestingTimes = that.TestingTimes + 1;

		that.requestTimes = setInterval(function () {
			if ($('#signalTesting').css("display") == "block") {
				that.TestingTimes = that.TestingTimes + 1
				if (!that.isShowStartBtn) { that.requestTesting(vesion, id); }
				if (that.TestingTimes >= parseInt(that.DetectionTimes)) {
					clearInterval(that.requestTimes);
					that.TestingTimes = 0;
					that.isShowStartBtn = true;
					return
				}
			} else {
				clearInterval(that.requestTimes);
				that.TestingTimes = 0;
				that.isShowStartBtn = true;
				return
			}
		}, parseInt(that.frequency) * 1000)
	}

	//终止查询接口
	endSubmit() {
		var that = this;
		that.isShowStartBtn = true;
		that.TestingTimes = 0;
		clearInterval(that.requestTimes);
	}
	//请求接口
	requestTesting(vesion, deviceId) {

		var that = this;
		var request = 'protocolVersion=' + vesion + '&deviceId=' + deviceId;
		this.jsonApiService.httpNotMessage("devicemanage/sendCodeForCheckGps.html", request).subscribe(data => {
			if (data.success && $('#signalTesting').css("display") == "block" && deviceId == data.data.code_deviceId) {
				that.echart_GPSData = []; //清空
				that.echart_NorthData = [];  //清空
				that.echart_GPS.clear();
				that.echart_North.clear();

				that.answerTimes = that.answerTimes + 1;
				var dataSource = data.data;

				//计算两个时间的分钟数
				if (dataSource.code_0408) {
					var time1 = this.interval(dataSource.code_0408, dataSource.code_0407);
					var time2 = this.interval(dataSource.code_0407, dataSource.code_0408);
					if (time1 >= 30) {
						dataSource.isShowRedTime = true;
					}
					if (time2 >= 30) {
						dataSource.isShowRedTime = true;
					}
				}

				that.SignalTestingData = dataSource;
				//GPS信噪比
				if (dataSource.code_04E0) {
					var code_04E0 = dataSource.code_04E0.split(',')
					var code_04E1 = dataSource.code_04E1.split(',')
					var code_04E2 = dataSource.code_04E2.split(',')
					var code_04E3 = dataSource.code_04E3.split(',')
					var code_04E4 = dataSource.code_04E4.split(',')
					var code_04E5 = dataSource.code_04E5.split(',')
					var code_04E6 = dataSource.code_04E6.split(',')
					var code_04E7 = dataSource.code_04E7.split(',')

					that.echart_GPSData = that.echart_GPSData.concat(code_04E0, code_04E1, code_04E2, code_04E3, code_04E4, code_04E5, code_04E6, code_04E7);
				}

				//北斗信噪比
				if (dataSource.code_04E8) {
					var code_04E8 = dataSource.code_04E8.split(',')
					var code_04E9 = dataSource.code_04E9.split(',')
					var code_04EA = dataSource.code_04EA.split(',')
					var code_04EB = dataSource.code_04EB.split(',')
					var code_04EC = dataSource.code_04EC.split(',')
					var code_04ED = dataSource.code_04ED.split(',')
					var code_04EE = dataSource.code_04EE.split(',')
					var code_04EF = dataSource.code_04EF.split(',')

					that.echart_NorthData = that.echart_NorthData.concat(code_04E8, code_04E9, code_04EA, code_04EB, code_04EC, code_04ED, code_04EE, code_04EF);
				}

				// console.log(that.echart_NorthData,'22222222')

				that.option_GPS.series[0].data = that.echart_GPSData;
				that.echart_GPS.setOption(that.option_GPS, true);
				that.echart_GPS.resize();

				that.option_North.series[0].data = that.echart_NorthData;
				that.echart_North.setOption(that.option_North, true);
				that.echart_North.resize();

				window.onresize = function () {
					if (that.echart_GPS) {
						that.echart_GPS.resize();
					}
					if (that.echart_North) {
						that.echart_North.resize();
					}
				}
			} else {
				// this.endSubmit();
				// this.jsonApiService.message(data.message);
			}
		})
	}
	interval(faultDate, completeTime) {

		var faultDate_time = faultDate.replace(/-/g, '/'); //必须把日期'-'转为'/'
		var faultDate_timestamp = new Date(faultDate_time).getTime();

		var completeTime_time = completeTime.replace(/-/g, '/'); //必须把日期'-'转为'/'
		var completeTime_timestamp = new Date(completeTime_time).getTime();

		var usedTime = completeTime_timestamp - faultDate_timestamp;  //两个时间戳相差的毫秒数
		var days = Math.floor(usedTime / (24 * 3600 * 1000));
		//计算出小时数
		var leave1 = usedTime % (24 * 3600 * 1000);    //计算天数后剩余的毫秒数
		var hours = Math.floor(leave1 / (3600 * 1000));
		//计算相差分钟数
		var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
		var minutes = Math.floor(leave2 / 1000); // 秒数

		return minutes;

	}

	/**
	 * 待维修的删除
	 */
	deleteRepaireRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			var reqdata = "id=" + row.id;
			this.jsonApiService.http('deviceRepaired/delDeviceRepairedById.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.getTabData('4_1');
			})
		})
	}


	/**
	 * 重量修正的下发数据请求
	 */
	setIssueData(status) {
		if (!this.weightFix.lastDate) {
			this.jsonApiService.message('推送时间不能为空');
			return;
		}
		var textLog, statusValue
		if (status == 1) {
			textLog = "是否停止推送数据?"
			statusValue = 0
		} else if (status == 0) {
			textLog = "是启动数据发送?"
			statusValue = 1
		}
		var reqdata = 'deviceId=' + this.selected[0].deviceId + "&lastDate=" + this.weightFix.lastDate + "&status=" + statusValue;
		this.jsonApiService.confirm_message(textLog).then(() => {
			this.jsonApiService.http('system/setSendStatus.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message)
				if (result.success) {
					this.weightFix.status = statusValue
				}
			})
		})
	}
	getIssueData() {
		var reqdata = 'deviceId=' + this.selected[0].deviceId;
		this.jsonApiService.http('system/getSendStatus.html', reqdata).subscribe(result => {
			if (result.success) {
				this.weightFix.status = result.data.status
				this.weightFix.lastDate = result.data.lastDate
			} else {
				this.jsonApiService.message(result.message);
			}
		})
	}

	// 数据导出
	exportData() {
		let params = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchKey: this.searchKey,
				company: this.selectedCompanyId,
				online: this.online,
				sort: this.sortType,
				filterType: this.filterType,
				useTypeL2: $('#TcarTypeSelect2').val() ? $('#TcarTypeSelect2').val() : '',
				useTypeL1: $('#TcarTypeSelect2').val() ? $('#TcarTypeSelect2').val().slice(0, 2) : ''
			},
			isExport: true
		}
		common.exprotDataFile(params, 'gridPager', config.BaseURL + 'system/realTimeData.html')
	}


	/**
	 * 限制进厂弹框
	 *
	 */
	limitIsPush: any = '0' //是否进厂限制 默认不限制
	limitPushTime: number = 6
	isPushTimeFlag: string = ''
	limitRowId = ''
	limitAutoReset(modal, row) {
		this.limitIsPush = row.isPush.toString()
		this.limitPushTime = 6
		modal.show()
		this.limitRowId = row.id
	}

	//确定批量进厂限制
	submitLimitModal(modal) {
		modal.show()
		let isPush = this.limitIsPush == 'time' ? '0' : this.limitIsPush
		let limitPushTime = this.limitIsPush == 'time' ? this.limitPushTime : ''

		let reqdata = {
			ids: this.limitRowId,
			isPush: isPush,
			time: limitPushTime
		}
		this.jsonApiService.http_obj('deviceRepaired/enterFactoryLimitBatch.html', reqdata).subscribe(data => {
			this.jsonApiService.message(data.message)
			if (data.success) {
				modal.hide()
				this.getTableDataTab('4_1')
			}
		})
	}
	//取消批量进厂限制
	cancelModalhide(modal) {
		modal.hide()
	}
	//自定义限制,校验非空值,默认6小时,不允许为空
	limitInputChange() {
		this.limitPushTime = Math.abs(Math.floor(this.limitPushTime))
		if (!this.limitPushTime) {
			this.limitPushTime = 6
		}
	}
	// 取消限制
	cancelRestrict(row) {
		this.jsonApiService.confirm_message('确定要取消自定义限制[' + row.restrictTime + '后限制]?').then(() => {
			let reqdata = 'id=' + row.id
			this.jsonApiService.http('deviceRepaired/removeRestrictions.html', reqdata).subscribe(data => {
				this.jsonApiService.message(data.message)
				if (data.success) {
					this.getTableDataTab('4_1')
				}
			})
		})
	}
}

